I am trying to get a crosstab of data so that the columns are months of the year and the rows are the years themselves based on value sold in that month.
Therefore:
year jan feb mar apr etc
2014 0 1 5 9
2015 11 12 0 14
using this SQL - (excuse the crudeness)
SELECT distinct
case
when year(fsivho.InvoiceDate) = 2014 then 2014
when year(fsivho.InvoiceDate) = 2015 then 2015
when year(fsivho.InvoiceDate) = 2016 then 2016
when year(fsivho.InvoiceDate) = 2017 then 2017
when year(fsivho.InvoiceDate) = 2018 then 2018
when year(fsivho.InvoiceDate) = 2019 then 2019
when year(fsivho.InvoiceDate) = 2020 then 2020
when year(fsivho.InvoiceDate) = 2021 then 2021
when year(fsivho.InvoiceDate) = 2022 then 2022
when year(fsivho.InvoiceDate) = 2023 then 2023
when year(fsivho.InvoiceDate) = 2024 then 2024
when year(fsivho.InvoiceDate) = 2025 then 2025
end as Month1,
(select sum(cast(fsivl.ShipQuantity * fsivl.InvoiceLocalUnitPrice as decimal(8,2))) as Value
from sqlinvline fsivl , sqlinvheaher fsivh
where fsivl.HeaderKey = fsivh.HeaderKey
and fsivh.InvoiceType = 'I'
and year(fsivh.InvoiceDate)* 100 + month(fsivh.InvoiceDate)
= year(fsivho.InvoiceDate)* 100 + month(fsivho.InvoiceDate)
and MONTH(fsivh.InvoiceDate) = 1
) as 'Jan',
(select sum(cast(fsivl.ShipQuantity * fsivl.InvoiceLocalUnitPrice as decimal(8,2))) as Value
from sqlinvline fsivl , sqlinvheaher fsivh
where fsivl.HeaderKey = fsivh.HeaderKey
and fsivh.InvoiceType = 'I'
and year(fsivh.InvoiceDate)* 100 + month(fsivh.InvoiceDate)
= year(fsivho.InvoiceDate)* 100 + month(fsivho.InvoiceDate)
and MONTH(fsivh.InvoiceDate) = 2
) as 'Feb',
from sqlinvline fsivlo , sqlinvheader fsivho
where fsivlo.HeaderKey = fsivho.InvoiceHeaderKey
and fsivho.InvoiceType = 'I'
and year(fsivho.InvoiceDate) >= year(DATEadd(yyyy, -2, GETDATE()))
group by YEAR(fsivho.InvoiceDate)
order by Month1
(I've shortened the code for brevity but the other months are formatted the same way)
When I run it, I get multiple lines for the years with an entry for a value against each month and the rest as nulls...e.g.
year jan feb mar apr etc
2014 nul 1 nul nul
2014 6 nul nul nul
2014 nul nul 7 nul
etc
What am I doing wrong?
all sorted by rewriting the query after many hours looking at pivot examples.
SELECT * from
(select year(fsivho.InvoiceDate) as Yr, cast(datename(MONTH ,fsivho.InvoiceDate) as CHAR(3)) as Mth,
cast(fsivlo.ShipQuantity * fsivlo.InvoiceLocalUnitPrice as decimal(8,2)) as Value
from ARInvoiceLine fsivlo , ARInvoiceHeader fsivho
where fsivlo.HeaderKey = fsivho.HeaderKey
and fsivho.InvoiceType = 'I'
and year(fsivho.InvoiceDate) >= year(DATEadd(yyyy, -4, GETDATE()))) src
PIVOT
(sum(Value)
for Mth in ([Jan],[Feb],[Mar],[Apr],[May],[Jun],[Jul],[Aug],[Sep],[Oct],[Nov],[Dec])) as pvt
order by Yr;
so now have rows of years with months across the top and values in the correct place!
I'm trying to figure out a way to query the last 12 completed months of data, so it would go up to last month and ignore this month.
I've done this before when the table had a date column, but this new table I'm working with separates the date into two month and year columns.
How would I go about this in SQL Server 2012?
Thanks in advance.
SAMPLE DATA:
CalendarYear CalendarMonth TotalSales
2014 3 35.00
2014 4 220.00
2015 2 243.00
2015 5 17.93
2015 6 216.36
2015 10 370.93
2015 12 350.00
2016 1 116.75
2016 2 13.78
DESIRED OUTPUT (assuming current time is in February 2016):
CalendarYear CalendarMonth TotalSales
2015 2 243.00
2015 5 17.93
2015 6 216.36
2015 10 370.93
2015 12 350.00
2016 1 116.75
I've assumed the Day part is always the 1st of the month.
WHERE
CONVERT(DATETIME, CalendarYear + '-' + CalendarMonth + '- 01') >= DATEADD(mm, -12, GETDATE())
The above assumes the columns are strings. Below I've done a version where the columns are numbers.
WHERE
CONVERT(DATETIME, CAST(CalendarYear AS NVARCHAR(4)) + '-' + CAST(CalendarMonth AS NVARCHAR(2)) + '-01') >= DATEADD(mm, -12, GETDATE())
You can just apply same code/logic to year and month you want data.
where to_date(year || month, 'YYYYMM')
between add_months(trunc(sysdate, 'MM'), -12) and trunc(sysdate)
How to get last 6 months month name, month number and Years in simple select statement in sqlserver .
The no of months is 6, and is fixed
12 Dec 2015
11 Nov 2015
10 Oct 2015
9 Sep 2015
8 Aug 2015
7 Jul 2015
6 Jun 2015
This should handle year end boundaries
say, if the current month is Feb 2016, the result should give 2015 months.
2 Feb 2016
1 Jan 2016
12 Dec 2015
11 Nov 2015
10 Oct 2015
9 Sep 2015
8 Aug 2015
You can do it with the following:
SELECT MONTH(DATEADD(mm, -m, GETDATE())) AS m,
LEFT(DATENAME(mm, DATEADD(mm, -m, GETDATE())), 3) AS n,
YEAR(DATEADD(mm, -m, GETDATE())) AS y
FROM (VALUES (0),(1),(2),(3),(4),(5),(6)) t(m)
Output:
m n y
12 Dec 2015
11 Nov 2015
10 Oct 2015
9 Sep 2015
8 Aug 2015
7 Jul 2015
6 Jun 2015
Try this
;with cte as
(
select 0 as num
union all
select num+1 from cte where num<6
)
select month(dates),datename(month,dates),year(dates)
from
(
select dateadd(mm,-num,datadd(dd,1,eomonth(getdate(),-1))) as dates
from cte
) A
SQL FIDDLE DEMO
select datepart(m,GETDATE()) MonthNumber,left(datename(month,GETDATE()),3) as Month,year(GETDATE()) as Year union all
select datepart(m,DATEADD(month,-1,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-1,GETDATE())),3) as Month,year(DATEADD(month,-1,GETDATE())) as Year union all
select datepart(m,DATEADD(month,-2,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-2,GETDATE())),3) as Month,year(DATEADD(month,-2,GETDATE())) as Year union all
select datepart(m,DATEADD(month,-3,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-3,GETDATE())),3) as Month,year(DATEADD(month,-3,GETDATE())) as Year union all
select datepart(m,DATEADD(month,-4,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-4,GETDATE())),3) as Month,year(DATEADD(month,-4,GETDATE())) as Year union all
select datepart(m,DATEADD(month,-5,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-5,GETDATE())),3) as Month,year(DATEADD(month,-5,GETDATE())) as Year union all
select datepart(m,DATEADD(month,-6,GETDATE())) MonthNumber,left(datename(month,DATEADD(month,-6,GETDATE())),3) as Month,year(DATEADD(month,-6,GETDATE())) as Year
The above query will work for most of the RDBMS.
For SQL Server specific use the below query.
SELECT MONTH(DATEADD(month, -month, GETDATE())) AS MonthNumber ,
LEFT(DATENAME(MONTH, DATEADD(month, -month, GETDATE())), 3) AS MonthName,
YEAR(DATEADD(month, -month, GETDATE())) AS Year
FROM ( VALUES (0), (1), (2), (3), (4), (5),(6) ) t ( month )
Try DATEADD:
Select * FROM Table where YourDate>=DATEADD(m, -6, GETDATE())
I have this SQL query, which gives me the numbers of orders within a date range, and that is OK:
SELECT CardName, ItemNumber, COUNT(*) AS antal, year(date) as aarstal, SUM(Numbers) AS total, sum(case when year(date)=2012 then 1 else 0 end) as newtest
FROM tblOrders
WHERE (Publisher = 3) AND (Date > '01-01-2012 00:00:00') AND (Date < '30-09-2014 23:59:59') AND (Status = 3) and ItemNumber!=9130 and ItemNumber!=9180 and ItemNumber!=9170 and ItemNumber!=9190
GROUP BY ItemNumber, CardName, year(date)
This gives me ie
CompanyA 0 76 2012 10900 76
CompanyA 0 42 2013 6300 0
CompanyB 0 1 2012 100 1
CompanyB 0 7 2013 1100 0
CompanyC 0 1 2014 300 0
CompanyD 0 7 2014 700 0
CompanyE 0 2 2012 300 2
CompanyE 0 1 2013 200 0
From this, I can see that CompanyA bought 10900 units in 2012, from a total of 76 orders that year, and in 2013, they bought 6300 units. For sales reasons, we would like (or need) this output as
CompanyA 0 76 2012 10900 42 2013 6300
CompanyB 0 1 2012 100 7 2013 1100
CompanyC 0 1 2014 300 0 2013 0
CompanyD 0 7 2014 700 0 2013 0
CompanyE 0 2 2012 300 1 2013 200
So you could see if a customer is going up or down in sales. I've tried various things, but I don't know if there is any possibility to have the Numbers column SUM'ed up per year in a query like this, any suggestions?
PS: The
sum(case when year(date)=2012 then 1 else 0 end) as newtest
was just for a test, I tried something like SUM(Numbers case...) but that was not accepted!
EDIT: I just made a demo in SQL Fiddle, just to give a better understanding of my problem:
http://sqlfiddle.com/#!3/072a1/5
In there, you can see that my customer A has bought a total of 300 in 2012 (on 2 orders), 700 in 2013 (on 2 orders), and finally 200 in 2014 (on 1 order). The pivot examples I've found only counts the number of orders, and not the value of my Numbers - could somebody edit the SQL Fiddle, making that one work, then I'm sure I could learn and adapt the solution into my "real" database?
/Tommy
I have two tables Distributors and Orders. I want to get the order counts for each month (INCLUDING 0 counts) I am Grouping by CustId Month and Year.
NOTE : The client is using SQL 2000 :(
This is what I want
DistID Month Year Orders
------------------------------
1 1 2012 4
1 2 2012 13
1 3 2012 5
2 1 2012 3
2 2 2012 0
2 3 2012 0
3 1 2012 8
3 2 2012 0
3 3 2012 3
4 1 2012 1
4 2 2012 0
4 3 2012 1
5 1 2012 6
5 2 2012 6
5 3 2012 0
This is what I get
DistID Month Year Orders
------------------------------
1 1 2012 4
1 2 2012 13
1 3 2012 5
2 1 2012 3
3 1 2012 8
3 3 2012 3
4 1 2012 1
4 3 2012 1
5 1 2012 6
5 2 2012 6
I know why. Its because there isnt a row in the Orders table for certain months. Is there a way to put a count of 0 if there arent any rows in the Orders table for that month and year?
Here is what I have so far
SELECT
D.DistID,
DATEPART(MONTH, Order_Date) AS [Month],
DATEPART(YEAR, Order_Date) AS [Year],
SUM(Total_PV) AS TotalPV,
COUNT(D.DistId) AS Orders
FROM Distributor D
LEFT OUTER JOIN Order O ON D.DistID = O.Distributor_ID
WHERE DATEPART(YEAR, Order_Date) > 2005
GROUP BY DistID, DATEPART(MONTH, Order_Date), DATEPART(YEAR, Order_Date)
Thanks for any input
You could create a table containing all months and years, like:
create table MonthList(year int, month int);
If you fill it with all available years, you can then left join:
select o.distributor_id
, ml.month
, ml.year
, sum(o.total_pv) as totalpv
, count(d.distid) as orders
from monthlist ml
left join
[order] o
on datepart(year, o.order_date) = ml.year
and datepart(month, o.order_date) = ml.month
where ml.year > 2005
group by
o.distributor_id
, ml.month
, ml.year
There is no need to join in Distributor if you don't use columns from that table.