Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Explode Final Resultset....

Author  Topic 

qman
Constraint Violating Yak Guru

442 Posts

Posted - 2013-08-09 : 11:17:04
How can I create a final result set that will break up a year into month columns, and display the appropriate amt under each month?

See below sample data

cust invoice_date amt
a 2011-06-30 00:00:00 4061
a 2011-07-31 00:00:00 1758
a 2011-08-31 00:00:00 1724
a 2011-09-30 00:00:00 1613
a 2011-10-31 00:00:00 1580
a 2011-11-30 00:00:00 1660
b 2011-10-31 00:00:00 878
b 2011-11-30 00:00:00 9986
...

Desired Result

cust Jun Jul Aug Sep Oct Nov Dec Jan Feb Mar Apr May
a 4061 1758 1724 1613 1580 1660 0 0 0 0 0 0
b 0 0 0 0 878 9986 0 0 0 0 0 0
...

qman
Constraint Violating Yak Guru

442 Posts

Posted - 2013-08-09 : 12:25:29
Figured it out via CTE....
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2013-08-09 : 12:34:50
Here is a quick pivot that might help in the future:
DECLARE @Foo TABLE (cust CHAR(1), invoice_date  DATETIME, amt INT)

INSERT @Foo
VALUES
('a', '2011-06-30 00:00:00', 4061),
('a', '2011-07-31 00:00:00', 1758),
('a', '2011-08-31 00:00:00', 1724),
('a', '2011-09-30 00:00:00', 1613),
('a', '2011-10-31 00:00:00', 1580),
('a', '2011-11-30 00:00:00', 1660),
('b', '2011-10-31 00:00:00', 878),
('b', '2011-11-30 00:00:00', 9986)


SELECT
cust,
COALESCE([Jun], 0) AS [Jun],
COALESCE([Jul], 0) AS [Jul],
COALESCE([Aug], 0) AS [Aug],
COALESCE([Sep], 0) AS [Sep],
COALESCE([Oct], 0) AS [Oct],
COALESCE([Nov], 0) AS [Nov],
COALESCE([Dec], 0) AS [Dec],
COALESCE([Jan], 0) AS [Jan],
COALESCE([Feb], 0) AS [Feb],
COALESCE([Mar], 0) AS [Mar],
COALESCE([Apr], 0) AS [Apr],
COALESCE([May], 0) AS [May]
FROM
(
SELECT
cust,
amt,
LEFT(DATENAME(MONTH, invoice_date), 3) AS invoice_date
FROM @Foo
) AS Source
PIVOT
(
MAX(amt)
FOR invoice_date IN ([Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec], [Jan], [Feb], [Mar], [Apr], [May])
) AS PivotTable
Go to Top of Page

qman
Constraint Violating Yak Guru

442 Posts

Posted - 2013-08-09 : 14:12:45
Thanks for the example.... Never used Pivot before, good to know..!
Go to Top of Page
   

- Advertisement -