February 13, 2013 at 1:39 am
Hi All,
Can anyone help me in below problem.
I have below result set
dtDatesDocIdPrefixCNT
2/11/20136533683
2/11/20136491334
2/12/20136471422
2/12/20136496602
2/12/20136534781
And i want it to be displayed as below
dtDate653649647
2/11/2013368313340
2/12/2013660266021422
Can Anyone please help on this . URGENT!!!!
Thanks in Advance.
February 13, 2013 at 5:09 am
If you provide test tables in the form of CREATE TABLE statements and sample data in the form of INSERT INTO statements I would be happy to provide some working code to help you solve the issue.
Without that I can refer you to this article:
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns By Jeff Moden][/url]
edit: fix url
There are no special teachers of virtue, because virtue is taught by the whole community.
--Plato
February 13, 2013 at 5:10 am
If it's really URGENT, then you better to present your issue in a way it could be quickly addressed. Please have a read tips from the link at the bottom of my signature.
DDL, sample data insert script and clear example of output (which you have already) will be very helpful.
Otherwise you need to wait for someone less lazy to do it for you. I can assure you that it will be definitely done, but it will take a bit longer than "URGENT" 🙂
February 13, 2013 at 8:50 am
IF object_id('tempdb..#testEnvironment') IS NOT NULL
BEGIN
DROP TABLE #testEnvironment;
END;
SELECT CAST(dtDate AS DATETIME) AS dtDate, sDocIdPrefix, CNT
INTO #testEnvironment
FROM (SELECT '2013-02-11', 653, 3683 UNION ALL
SELECT '2013-02-11', 649, 1334 UNION ALL
SELECT '2013-02-12', 647, 1422 UNION ALL
SELECT '2013-02-12', 649, 6602 UNION ALL
SELECT '2013-02-12', 653, 4781
)a(dtDate,sDocIdPrefix,CNT);
Sample data is: -
dtDate sDocIdPrefix CNT
----------------------- ------------ -----------
2013-02-11 00:00:00.000 653 3683
2013-02-11 00:00:00.000 649 1334
2013-02-12 00:00:00.000 647 1422
2013-02-12 00:00:00.000 649 6602
2013-02-12 00:00:00.000 653 4781
Using the sample data above, then I think that this is what you're after: -
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = 'SELECT dtDate,' + sqlCode + CHAR(13) + CHAR(10) + 'FROM #testEnvironment'+CHAR(13)+CHAR(10)+'GROUP BY dtDate;'
FROM (SELECT STUFF((SELECT ',' + CHAR(13)+CHAR(10)+
'MAX(CASE WHEN sDocIdPrefix = ' + CAST(sDocIdPrefix AS VARCHAR(20)) + ' THEN CNT ELSE 0 END) AS '+
QUOTENAME(CAST(sDocIdPrefix AS VARCHAR(20)))
FROM (SELECT DISTINCT sDocIdPrefix
FROM #testEnvironment
)a
ORDER BY sDocIdPrefix DESC
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)'),1,1,'')
)dynSql(sqlCode)
EXECUTE sp_executesql @sql;
Produces: -
dtDate 653 649 647
----------------------- ----------- ----------- -----------
2013-02-11 00:00:00.000 3683 1334 0
2013-02-12 00:00:00.000 4781 6602 1422
Look at how I laid out the sample data, it makes it considerably easier for people to help when it looks like that
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply