For each of the 12 months, I'm looking to create a field that sums the sales dollars at the account level for the most recent month and the 2nd most recent month based on the current date.
For example, given that today's date is 2022-10-28, 'MostRecentNovember' would sum up sales from November 2021. '2ndMostRecentNovember' would sum up sales from November 2020. Once the current date moves into November 2022, this query would adjust to pull MostRecentNovember sales from 2022 and 2ndMostRecentNovember sales from 2021.
Conversely, given that today's date is 2022-10-28 'MostRecentJune' would sum up sales from June 2022 and '2ndMostRecentJune' would sum up sales from June 2021.
In the end state, each account would have 24 fields: January - December for Most Recent and January - December for 2nd most recent
Below is my attempt at this code, this gets partially there, but it's not getting what I need. I've also tried with a CTE, but that didn't seem to do it either
SELECT NovemberMostRecent_Value =
sum(case when datepart(year,tran_date) = datepart(year, getdate())
AND DATEPART(month, tran_date) = 11 then value else 0 end)
NovemberSecondMostRecent_Value =
sum(case when datepart(year,tran_date) = datepart(year, getdate())-1
AND DATEPART(month, tran_date) = 11 then value else 0 end)
Here's a snippet of the source data table
account_no
tran_date
value
123
2021-11-22
500
123
2021-11-01
500
123
2020-11-20
1500
123
2022-06-03
5000
123
2021-06-04
2000
456
2020-11-03
525
456
2021-11-04
125
A table of desired Results
account_no
NovemberMostRecent
November2ndMostRecent
June MostRecent
June2ndMostRecent
123
1000
1500
5000
2000
456
125
525
0
0
We use dense_rank() by year desc (partitioned by month) and pivot.
select *
from
(
select account_no
,value
,concat(datename(month, tran_date), '_', dense_rank() over(partition by month(tran_date) order by year(tran_date) desc)) as month_rnk
from t
) t
pivot (sum(value) for month_rnk in(June_1, June_2, November_1, November_2)) p
account_no
June_1
June_2
November_1
November_2
123
5000
2000
1000
1500
456
null
null
125
525
Fiddle
So I have 2 tables in web SQL , one of them looks like this(there are thousands of rows):
customer_number | order_number
--------------------------------------------
1234 12
1234 13
1234 14
6793 20
6793 22
3210 53
etc.
And the other table like this(also thousands of rows):
customer_number | first_purchase_year
----------------------------------------------------
1234 2010
5313 2001
1632 2018
9853 2017
6793 2000
3210 2005
etc.
I have this code to select 10 customers from the first table and list all their purchases:
select top 10 * from
(select distinct t1.customer_number,
stuff((select '' + t2.order_number
from orders t2
where t1.customer_number = t2.customer_number
for xml path(''), type
).value('.','NVARCHAR(MAX)')
,1,0,'')DATA
from orders t1) a
Whch outputs this:
customer_number | order_number
--------------------------------------------
1234 12 13 14
6793 20 22
3210 53
What I need to do is ONLY display 10 random customers that have first_purchase_year > 2010.
I am not sure how to check if first_purchase_year corresponding to a customer_number is greater than 2010.
Thank you!
You just need to fix the subquery in the outer from clause:
select c.customer_number,
stuff((select '' + o2.order_number
from orders o2
where c.customer_number = o2.customer_number
for xml path(''), type
).value('.','NVARCHAR(MAX)'
), 1, 0, ''
) as data
from (select top (10) c.customer_number
from table2 c
where c.first_purchase_year > 2010
) c;
I have a record for project and release number and I need to repeat the row in next year if value is recurring.
First image is showing the data that I have it
My expected output is:
Explanation of output: In year 2017 value_type ITA has frequency as Recurring so, This value should be repeated in all next year(i.e 2018, 2019 and 2020). like that in year 2018 OC and PA is recurring so it also need to repeated in 2019 and 2020.
For that I created a new view for only recurring value and tried to join that view with base table. But it is not giving me proper result.
Can anyone please help me with this?
Thanks in advance..
DECLARE #EndYear INT =2020 --Also you can get from data by MAX(Year)
;WITH tb(PROJECT_ID,RELEASE_NO,[YEAR],VALUE_TYPE,VAL_DES,COST,RUN_TATE,FREQUENCY)
AS(
SELECT 111,1,2016,'IT','EXPENSE',0,NULL,NULL UNION
SELECT 111,1,2016,'IR','INCOME',10000,NULL,NULL UNION
SELECT 111,1,2016,'OC','EXPENSE',-200000,NULL,NULL UNION
SELECT 111,1,2016,'Vendor','EXPENSE',-5000,NULL,NULL UNION
SELECT 111,1,2017,'BC','INCOME',200000,NULL,NULL UNION
SELECT 111,1,2017,'ITA','INCOME',5000,5000,'Recurring' UNION
SELECT 111,1,2017,'OC','EXPENSE',-200000,NULL,NULL UNION
SELECT 111,1,2018,'OC','EXPENSE',-10000,-10000,'Recurring' UNION
SELECT 111,1,2018,'PA','INCOME',100000,100000,'Recurring' UNION
SELECT 111,1,2019,'icc','INCOME',500,NULL,NULL UNION
SELECT 111,1,2020,NULL,NULL,NULL,NULL,NULL
),Recurring AS (
SELECT tb.PROJECT_ID,tb.RELEASE_NO,tb.VALUE_TYPE,tb.VAL_DES,MIN([YEAR]) AS StartYear,MAX(COST) AS COST,MAX(tb.RUN_TATE) AS RUN_TATE
FROM tb WHERE FREQUENCY='Recurring'
GROUP BY tb.PROJECT_ID,tb.RELEASE_NO,tb.VALUE_TYPE,tb.VAL_DES
)
SELECT * FROM tb union
SELECT r.PROJECT_ID,r.RELEASE_NO,n.number AS [YEAR],r.VALUE_TYPE,r.VAL_DES,r.COST,r.RUN_TATE,NULL AS FREQUENCY FROM
Recurring AS r
OUTER APPLY (
SELECT sv.number FROM master.dbo.spt_values AS sv WHERE sv.type='P' AND sv.number BETWEEN r.StartYear+1 AND #EndYear
)n
PROJECT_ID RELEASE_NO YEAR VALUE_TYPE VAL_DES COST RUN_TATE FREQUENCY
----------- ----------- ----------- ---------- ------- ----------- ----------- ---------
111 1 2016 IR INCOME 10000 NULL NULL
111 1 2016 IT EXPENSE 0 NULL NULL
111 1 2016 OC EXPENSE -200000 NULL NULL
111 1 2016 Vendor EXPENSE -5000 NULL NULL
111 1 2017 BC INCOME 200000 NULL NULL
111 1 2017 ITA INCOME 5000 5000 Recurring
111 1 2017 OC EXPENSE -200000 NULL NULL
111 1 2018 ITA INCOME 5000 5000 NULL
111 1 2018 OC EXPENSE -10000 -10000 Recurring
111 1 2018 PA INCOME 100000 100000 Recurring
111 1 2019 icc INCOME 500 NULL NULL
111 1 2019 ITA INCOME 5000 5000 NULL
111 1 2019 OC EXPENSE -10000 -10000 NULL
111 1 2019 PA INCOME 100000 100000 NULL
111 1 2020 NULL NULL NULL NULL NULL
111 1 2020 ITA INCOME 5000 5000 NULL
111 1 2020 OC EXPENSE -10000 -10000 NULL
111 1 2020 PA INCOME 100000 100000 NULL
I have a table like the following-
year month frequency
---------- ---------- ----------
2501 04 33
2501 03 911
2503 12 377
2503 11 3956
2503 10 1409
2503 07 161
2503 06 66
2504 03 46
How to get the most frequent month of each year to produce
year month frequency
---------- ---------- ----------
2501 03 911
2503 11 3956
2504 03 46
Possible solution is to use join :
select t1.*
from t t1 join (select year, max(freq) freq from t group by year) t2
on t1.year = t2.year and t1.freq = t2.freq
SQLFiddle
The following query provides your solution. SQLFiddle here.
select year, month, max(frequency) frequency
from mytable
group by year
UPDATE:
Your required output had columns year, month, frequency where frequency was the maximum value of frequency per year. So max(frequency) frequency assigns the alias frequency to the query output so that it matches your requirement. Without the alias, the columns would be year, month, max(frequency). Here is the wiki on SQL aliases.
I've following query which display the result as required, but I need to get the missing Primary Key Values missing in the result:
SELECT
tbl1.SignedByUserID, tbl2.FullName,
COUNT(tbl1.OutletID) AS TotalSignups,
DATENAME(Month, tbl1.SignupDate) AS Month
FROM
dbo.tblMer_Outlet AS tbl1
LEFT OUTER JOIN
dbo.tblGen_Users AS tbl2 ON tbl1.SignedByUserID = tbl2.UserID
WHERE
(tbl1.SignupDate >= '2014-04-01 00:00:00'
AND tbl1.SignupDate <= '2014-04-30 23:59:59')
GROUP BY
tbl1.SignedByUserID, tbl2.FullName, DATENAME(Month, tbl1.SignupDate)
ORDER BY
tbl2.FullName
This query returns the following result:
SignedByUserID FullName TotalSignups Month
--------------------------------------------------------
9 Babu Raj 16 April
11 Faheem 19 April
39 Fasil Abbas 16 April
29 Hafiz Suleman 10 April
12 Hussain Abbas 16 April
15 Khawaja Aashan 33 April
33 M. Danyal 16 April
41 M. Qasim 01 April
32 M. Yousuf 16 April
37 Noman Yousaf 14 April
40 Sajid Saleem 16 April
5 Sales 10 April
20 Tauseef Anees 23 April
35 Umar Akbar 11 April
22 Willie 09 April
but my User table contains 1 more value:
38 Bilal Mateen
which does not have a signup for the month of April, but I need it to be available for this or any upcoming month.
Not specific to the user. Thanks in advance!
Finally got it fixed...
SELECT A.UserID, A.FullName, ISNULL(B.TotalSignups,0) AS TotalSignups, B.Month FROM
(
SELECT UserID, FullName
FROM tblGen_Users
WHERE GroupID = 4
) AS A LEFT OUTER JOIN
(
SELECT SignedByUserID, COUNT(1) AS TotalSignups, DATENAME(Month, SignupDate) AS Month
FROM tblMer_Outlet
WHERE SignupDate BETWEEN '2014-04-01' AND '2014-05-01'
GROUP BY SignedByUserID, DATENAME(Month, SignupDate)
) AS B ON A.UserID = B.SignedByUserID
ORDER BY A.FullName
If needs some improvement, please suggest.