Create Groups based on revenue and year in SQL Server - sql-server

I have a scenario to cover in SQL stated below.
Any help would be appreciated.
Segment all customers in the data using the following rules. The groups should be mutually exclusive i.e. one customer should fall only in one group and a higher-ranked group gets priority (ex. If a customer falls in group 1 and group 3 then group 1 gets priority)
Group 1: Customers with >2000 total revenue in last 1-year
Group 2: Customers with >2000 total revenue in last 2 years
Group 3: Customers with >2000 total revenue in any 2 consecutive years (in the entire data provided)
Group 4: Customers with <2000 in last 2 years
Group 5: Customers with 0 revenue in the last 2 years

Related

SQL Server - Aggregate previous 5 months sales data to current month [duplicate]

This question already has answers here:
Rolling sum previous 3 months SQL Server
(3 answers)
Closed 4 years ago.
I need to aggregate sales of previous five months to current month for each record. In the table below for example,
StoreID |Month |Sales
-----------|----------|----------
119119 |201802|50000
119119 |201803|62500
119119 |201804|93750
119119 |201708|45000
119271 |201803|25000
119271 |201804|75000
119271 |201802|50000
StoreID 119119's aggregated sales for Month 201804 should be 50000+62500+93750.
Aggregated sales for 119119 for Month 201803 should be 62500+50000 and so on.
I need to do this so that I will be able to plot this aggregated column on a time-series graph.
I cannot use ASC ROWS 5 PRECEEDING here because there may not be sales data for every month and I should not aggregate previous 5 records but it should be strictly based on previous 5 months sales data.
Is it possible to do this without using cursors? Can someone suggest a solution?
You can use a self join to get the older values. ie:
DECLARE #stores TABLE(StoreID INT, [Month] VARCHAR(6), Sales INT);
INSERT INTO #stores(StoreID, Month, Sales)
VALUES(119119, '201802', 50000),
(119119, '201803', 62500),
(119119, '201804', 93750),
(119119, '201708', 45000),
(119271, '201803', 25000),
(119271, '201804', 75000),
(119271, '201802', 50000);
WITH
Sales AS (SELECT StoreID, CAST([Month]+'01' AS DATE) AS [Month], Sales FROM #stores)
SELECT s1.StoreID, s1.[Month], SUM(s2.Sales) AS total
FROM Sales s1
inner JOIN Sales s2 ON s1.StoreID=s2.StoreID
AND s1.[Month]>=s2.[Month]
AND DATEDIFF(MONTH, s2.[Month], s1.[Month])<5
GROUP BY s1.StoreID, s1.[Month]
ORDER BY s1.StoreID, s1.[Month];

How to create a T-SQL query to sum quantity sold per item during a deal period when the sales data is split into multiple tables by month and year

How to create a T-SQL query to sum quantity sold per item during a deal period when the sales data is split into multiple tables by month and year.
I created a simple table name PITEMS that contains 3 columns item_no, start_date and end_date of the promotion.
ITEM_NO START_DATE END_DATE
-------------------------------
1001 02/25/16 03/25/16
4512 03/01/16 03/31/16
1753 04/10/16 04/28/16
9804 05/01/16 09/10/16
Then to calculate quantity sold for item 1001. I would first have to gather all the data from 2 tables ITEM_SOLD_022016 and ITEM_SOLD_032016 for item 1001.
Then I have to sum the quantity that was sold between 02/25/2016 and 03/25/2016.
For item 9804 I would have to combine data from 5 tables.
ITEM_SOLD_052016
ITEM_SOLD_062016
ITEM_SOLD_072016
ITEM_SOLD_082016
ITEM_SOLD_092016

SQL Server - Select top 10 providers based on charge amounts from 3rd quarter

I'm having some trouble figuring out what I need to do to make this work and meet these requirements:
Generate a SELECT statement that figures out the top 10 providers from
the credit db based on total charge amounts from the 3rd quarter.
Here's what I have so far:
select top 10 provider_no, charge_amt, charge_dt
from charge
group by provider_no
order by charge_amt desc;
Could I get some help finishing this query so it shows only 10 lines and doesn't have repeating provider_no's sorted by the charge_amt with the charge_dt in the 3rd quarter of the year?
I assume that charge_dt is a date time of the charge. So the statement should look like:
select top 10 provider_no, datepart(qq, charge_dt), sum(charge_amt)
from charge
where datepart(qq, charge_dt) = 3
group by provider_no, datepart(qq, charge_dt)
order by sum(charge_amt) desc

Need a SQL query to get data from SQL Server database for a given period with certain condition

I have a SQL Server database with a table dbo.sales with 7 columns.
First column contains different sales person names, on column 2 to 6 other information, on column 7, sales average.
Question: what I need is a query to get all sales person details (all seven columns in Excel) if their sales average is more than 60% between a given date.
For example: in my database, I have data from 01/05/2016 to 31/05/2016, if I enter a period in my Excel sheet between 25/05/2016 to 31/05/2016 and my required average for ex. 60% (should be changed as per my need), then I need all the sales person details who continuously have sales average of more than 60% between 25 to 31st May 2016.
If a sales man average was dropped below 60% on 28th May, then I don't want to see him on my report. In simple words, I need all sales person who continuously hitting 60% or more on average sales within my search period.
Not sure if the sales period date is within the table, but if it is, that query should work for you:
;WITH PeriodSales as (
SELECT * FROM Sales
WHERE SalseDate between #StartDt and #EndDt)
SELECT * FROM PeriodSales
WHERE SalesPerson not in (
SELECT SalesPerson FROM PeriodSales
WHERE CASE WHEN IsNumeric(salesavg) = 1
THEN CAST(salesavg as Decimal) ELSE 0 END <= 60.
);

T-SQL Group by / Order by + SQL Server Reporting Service Parameters

select
Users.UserId
,Users.FirstName + ' ' + Users.LastName AS
,[Month]
,[Day]
,x.[Przych]
,x.[Wych]
,x.[Przych] + [Wych] as [Ogół]
from
(select
CaseActionHistory.UserId
,month(CaseActionHistory.DateAdded) AS [Month]
,day(CaseActionHistory.DateAdded) AS [Day]
,sum(case when CaseActionHistory.CaseActionDefinitionId in (14,15,16) then 1 else 0 end) AS [Przych]
,sum(case when CaseActionHistory.CaseActionDefinitionId in (20,21,22,23,26) then 1 else 0 end) AS [Wych]
from CaseActionHistory
where CaseActionHistory.CaseActionDefinitionId in (14,15,16,20,21,22,23,26)
group by month(CaseActionHistory.DateAdded),day(CaseActionHistory.DateAdded), CaseActionHistory.UserId
order by month(CaseActionHistory.DateAdded) DESC,day(CaseActionHistory.DateAdded) DESC
OFFSET 0 rows
) AS x
inner join Users on x.UserId = Users.UserId
I'm trying to run out something out of this. My problem is: the results of such query are displayed like this:
User Month Day X
User1 7 31 6
User2 7 31 7
User3 7 31 9
User1 7 30 8
User2 7 30 7
User3 7 30 8
User4 7 31 10
User5 7 31 20
User6 7 31 23
User4 7 30 5
User5 7 30 7
User6 7 30 65
So in fact few Users are grouped into small groups which are displayed first, then 2nd group, etc. so I suppose there's a problem either with group by or order by.
As an addition I'd like to ask a question concerning parameters in SQL Server. Out of code below I'd like to set up 3 parameters:
User
Month
Day
But my problem is that when I set up details of parameter and I run it some values are multiplied. Same user is multiplied few times, same month, same day etc. also report itself is not reacting on any kind of change within parameters.
The main idea of a report is to show the number of phone calls done by every employee, each day, every month and to be able to compare results with others.
Calls are splitted into: outgoing and incoming. After every phone call employee adds to system an information regarding what phone call it was and what they managed to do during this phone call.
So in fact we are working on 2 tables in this case:
CaseActionHistory and Users
So the plan was to show the number of phone calls (incoming, outgoing and sum of those) for every day for every person.
Since CaseActionHistory table consits only ID of User which done the action and I'd like to show the person's name (which is placed in Users table obviously).
The problem is that the report should show around 20 Users one by one, so for 31st of June 20 Users one by one, for 30th 20 Users one by one etc, but it shows like 5 Users for 31st, then same Users for 30th, then next 5 Users for 31st etc (link to image showing the situation below)
http://img801.imageshack.us/img801/2088/7blu.png
Columns are:
UserId (to be replaced with UserName) Day Month Incming Outgoing Sum
The rows on the bottom for 31st July should be on the top of the list but they are not.
Welcome to stack overflow. A few things:
If your data is 'multiplying' may you just do a 'distinct' in your main select statement and determine if it is not your dataset repeating?
How are you applying parameters? They should be predicates and have nothing to do with groupings except indirectly. You may limit a set by a parameter but it will not affect your grouping directly, generally speaking.
What do you want to group by? Year, Month, (detail)?
SSRS starts out with a data connection (Data Source). You then apply a Data Set which is a query or proc. Which you have a query. You can apply a predicate to the main dataset with a 'where User = #User' or 'where User in (#User)'. The parameter will automatically be created if you do this in your dataset first with the '#(something)' creating a text parameter of said name. You see the Built In Fields, Parameters, Images, Data Sources, DataSets in the 'Report Data' view which you will use constantly in SSRS creation with 'Business Intelligence Development Studio'.
So a simple example would be that you want to add a group for the Day to your '(Details)' row. If you create a 'Table' element from the 'Toolbox' it will only have a single row called Details. Fill it with your X value and user. In the 'Design' surface at the bottom you will see 'Row Groups'. Right click on your 'Details' row and choose add parent group. Group by 'Day' check 'Add Group Header'. You now have another row that will be grouping by Day. You can repeat this process on the newly created group for a group for 'Month' and so and so on.

Resources