Tuesday 28 October 2014

Pivot in sql

Create table
------------------------------
CREATE TABLE [dbo].[att](
[uid] [int] NOT NULL,
[status] [varchar](5) NULL,
[adate] [date] NULL
) ON [PRIMARY]

GO


PIVOT QUERY
------------------------------------
Select uid,PVTTable.[2014-10-1] as '1',PVTTable.[2014-10-2] as '2',PVTTable.[2014-10-3] as

'3',PVTTable.[2014-10-4] as '4',PVTTable.[2014-10-5] as '5',PVTTable.[2014-10-6] as '6',PVTTable.

[2014-10-7] as '7',PVTTable.[2014-10-8] as '8',PVTTable.[2014-10-9] as '9',PVTTable.[2014-10-10]

as '10',PVTTable.[2014-10-11] as '11',PVTTable.[2014-10-12] as '12',PVTTable.[2014-10-13] as

'13',PVTTable.[2014-10-14] as '14',PVTTable.[2014-10-15] as '15',PVTTable.[2014-10-16] as

'16',PVTTable.[2014-10-17] as '17',PVTTable.[2014-10-18] as '18',PVTTable.[2014-10-19] as

'19',PVTTable.[2014-10-20] as '20',PVTTable.[2014-10-21] as '21',PVTTable.[2014-10-22] as

'22',PVTTable.[2014-10-23] as '23',PVTTable.[2014-10-24] as '24',PVTTable.[2014-10-25] as

'25',PVTTable.[2014-10-26] as '26',PVTTable.[2014-10-27] as '27',PVTTable.[2014-10-28] as

'28',PVTTable.[2014-10-29] as '29',PVTTable.[2014-10-30] as '30',PVTTable.[2014-10-31] as '31'

from att PIVOT(count(adate) FOR adate IN ([2014-10-1],[2014-10-2],[2014-10-3],[2014-10-4],

[2014-10-5],[2014-10-6],[2014-10-7],[2014-10-8],[2014-10-9],[2014-10-10],[2014-10-11],[2014-10-

12],[2014-10-13],[2014-10-14],[2014-10-15],[2014-10-16],[2014-10-17],[2014-10-18],[2014-10-19],

[2014-10-20],[2014-10-21],[2014-10-22],[2014-10-23],[2014-10-24],[2014-10-25],[2014-10-26],

[2014-10-27],[2014-10-28],[2014-10-29],[2014-10-30],[2014-10-31])) AS PVTTable



No comments:

Post a Comment