Pivoting SQL Server result set - sql
if I have a result returned as follows:
pkTestInstanceID Percent1 Count1 Percent2 Count2
1 25 1 75 3
2 50 2 50 2
Is there a way so it pivots in such format:
pkTestInstanceID Percent Count
1 25 1
1 75 3
2 50 2
2 50 2
Sorry if this question is totally misguided. I'm not super clear on the pivoting process. Thanks for any help.
EDIT I should probably have noted that the Percent1, Count1, Percent2 etc columns are created based off of another column (stackposition). So if stackposition has 4 rows then the percent and count will go up to percent4 count4. Is a pivot or union still possible without the knowledge of the exact number of percent and count columns in the result set.
EDIT 2: It gets a bit more complicated now...
I now realize that I have to include another item in my select statement (fkBandID). For each bandID there is a stackposition as stated above, so for bandID 96 the stackposition is 4, for 97 the stackposition is 3, for 98 the stackposition is 2 etc. so I want the result set to look as follows:
fkBandID pkTestInstanceID Band_Percent Band_Count StackPosition (not included but there for for visual example)
96 265 2 1 4
97 265 4 2 3
98 265 34 17 2
99 265 59 29 1
Here is what the creation of my second query looks like after the initial result set is brought back and with the bandID being selected including the new bandID. This is from Pradeep's answer.
http://gyazo.com/091ece1a4a1334c0f2546bccb8a6b8da
This is what the result set looks like, so as you can see there are 4 rows being created for each bandID. Is there anyway to fix this and make it look as I displayed above in the cross apply that Pradeep helped me with? Or any other solution?
http://gyazo.com/cd19634a1201362ac3aa4546f15373c9
Sorry I'm super nooby with SQL. Let me know if more info is needed.
EDIT 3
(N'DECLARE #strYearIds nvarchar(100)
SET #strYearIds = ''' + #strYearIds + N'''
DECLARE #strDemoCodeIds nvarchar(100)
SET #strDemoCodeIds = ''' + #strDemoCodeIds + N'''
DECLARE #intRosterSetId int
SET #intRosterSetId = ' + CONVERT(nvarchar, #intRosterSetId) + N'
DECLARE #intSchoolId int
SET #intSchoolId = ' + CONVERT(nvarchar, #intSchoolId) + N'
DECLARE #intTeachId int
SET #intTeachId = ' + CONVERT(nvarchar, #intTeachId) + N'
DECLARE #intGradeId int
SET #intGradeId = ' + CONVERT(nvarchar, #intGradeId) + N'
DECLARE #intDeptId int
SET #intDeptId = ' + CONVERT(nvarchar, #intDeptId) + N'
DECLARE #intCourseId int
SET #intCourseId = ' + CONVERT(nvarchar, #intCourseId) + N'
DECLARE #intPeriodId int
SET #intPeriodId = ' + CONVERT(nvarchar, #intPeriodId) + N'
DECLARE #strTestInstId nvarchar(100)
SET #strTestInstId = ''' + #strTestInstId + N'''
DECLARE #intTestTypeId int
SET #intTestTypeId = ' + CONVERT(nvarchar, #intTestTypeId) + N'
DECLARE #strSubIds nvarchar(100)
SET #strSubIds = ''' + #strSubIds + N'''
DECLARE #bitIsStrand bit
SET #bitIsStrand = ' + CONVERT(nvarchar, #bitIsStrand) + N'
DECLARE #intPerfLevelReportId int
SET #intPerfLevelReportId = ' + CONVERT(nvarchar, #intPerfLevelReportId) +
N' DECLARE #tempTests TABLE (id int)
INSERT INTO #tempTests
exec SPGetStudentTests_Local_MTI #strDemoCodeIds, #strYearIds, #intSchoolId, #intTeachId, #intGradeId,
#intRosterSetId, #intPeriodId, #intDeptId, #intCourseId, #strTestInstId, #intTestTypeId
DECLARE #tempSubs TABLE (id int)
IF #bitIsStrand = 1
BEGIN
INSERT INTO #tempSubs
SELECT pkTestSubjectID FROM MM_Test_Subjects WHERE fkCSTStrandID /*= #intSubID*/ IN (SELECT number FROM itot(#strSubIds, N'','')) AND fkTestTypeID = #intTestTypeId
END
ELSE
BEGIN
INSERT INTO #tempSubs
SELECT number FROM itot(#strSubIds, N'','')--VALUES (#intSubId)
END
SELECT bands.pkPerformanceLevelReportBandID AS ''fkBandID'', TestInstances.pkTestInstanceID AS ''TestInstanceID'', StudentScores_Subject.fkTest_SubjectID AS ''TestSubjectID'', '
+ #cols +
N'INTO ##tempTable FROM StudentScores_Subject
INNER JOIN StudentTests ON StudentScores_Subject.fkStudentTestID = StudentTests.pkStudentTestID
INNER JOIN TestInstances ON TestInstances.pkTestInstanceID = StudentTests.fkTestInstanceID
INNER JOIN CAHSEE_TestPeriods ON CAHSEE_TestPeriods.pkTestPeriodID = TestInstances.fkTestPeriodID
INNER JOIN PerformanceLevelReportBands bands ON bands.fkPerformanceLevelReportID = #intPerfLevelReportId
LEFT JOIN MMARS_Web_TestInfo_California.dbo.PerfLevelReportBandCutScores cutScores ON cutScores.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND cutScores.fkGradeID = #intGradeId
AND cutScores.fkTestSubjectID IN (SELECT id FROM #tempSubs)
INNER JOIN PerfLevelReportBandComponents bandComponents ON bandComponents.fkPerformanceLevelReportBandID = bands.pkPerformanceLevelReportBandID
AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR
((CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN bandComponents.minScore and bandComponents.maxScore)
OR
(CAST(StudentScores_Subject.ScoreValue AS INT) BETWEEN cutScores.minScore and cutScores.maxScore))
)
RIGHT JOIN MM_SchoolYears ON MM_SchoolYears.pkSchoolYearID = TestInstances.fkSchoolYearID
WHERE MM_SchoolYears.pkSchoolYearID IN (SELECT number FROM itot(#strYearIds, N'',''))
AND bands.fkPerformanceLevelReportID = #intPerfLevelReportId
AND StudentScores_Subject.fkStudentTestID IN (SELECT id FROM #tempTests)
AND StudentScores_Subject.fkScoreTypeID = bandComponents.fkScoreTypeID
AND StudentScores_Subject.fkTest_SubjectID IN (SELECT id FROM #tempSubs)
--AND((bandComponents.ScoreValue = StudentScores_Subject.ScoreValue) OR
--(StudentScores_Subject.ScoreValue BETWEEN bandComponents.minScore and bandComponents.maxScore) OR
--(StudentScores_Subject.ScoreValue BETWEEN cutScores.minScore and cutScores.maxScore))
GROUP BY bands.pkPerformanceLevelReportBandID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID
ORDER BY bands.pkPerformanceLevelReportBandID, TestInstances.pkTestInstanceID, StudentScores_Subject.fkTest_SubjectID')
The #cols variable is as follows:
DECLARE #cols NVARCHAR(MAX)
SELECT #cols = STUFF(( SELECT DISTINCT TOP 100 PERCENT ', SUM(CASE WHEN bands.StackPosition = ''' + STR(b.StackPosition, 1) + ''' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS ''Percent_' + STR(b.StackPosition, 1) + ''', SUM(CASE WHEN bands.StackPosition = ''' + STR(b.StackPosition, 1) + ''' THEN 1 ELSE 0 END) AS ''Count_' + STR(b.StackPosition, 1) + ''''
FROM PerformanceLevelReportBands AS b
WHERE b.fkPerformanceLevelReportID = #intPerfLevelReportId
ORDER BY ', SUM(CASE WHEN bands.StackPosition = ''' + STR(b.StackPosition, 1) + ''' THEN 1 ELSE 0 END) * 100.0/ CASE WHEN COUNT(pkStudentScoreID) = 0 THEN 1 ELSE COUNT(pkStudentScoreID) END AS ''Percent_' + STR(b.StackPosition, 1) + ''', SUM(CASE WHEN bands.StackPosition = ''' + STR(b.StackPosition, 1) + ''' THEN 1 ELSE 0 END) AS ''Count_' + STR(b.StackPosition, 1) + ''''
FOR XML PATH('')
), 1, 2, '')
what you are looking for is Unpivot not pivot
CREATE TABLE #piv
(
pkTestInstanceID INT,
Percent1 INT,
Count1 INT,
Percent2 INT,
Count2 INT
)
INSERT INTO #piv
VALUES ( 1,25,1,75,3),
(2,50,2,50,2)
SELECT pkTestInstanceID,
[percent],
[count]
FROM #piv AS p
CROSS APPLY ( VALUES (Percent1,Count1),
(Percent2,Count2))
AS x([percent], [count]);
If you want this to work dynamically then below code should help you.
For example i have kept no. of stackposition rows as 2 u can change it and check
DECLARE #stackposition INT=2,
#sql NVARCHAR(max),
#cnt INT=1
SET #sql =' SELECT pkTestInstanceID,
[percent],
[count]
FROM #piv AS p
CROSS APPLY ( VALUES '
WHILE #cnt <= #stackposition
BEGIN
SET #sql+='([Percent' + CONVERT(VARCHAR(10), #cnt)+ '],[Count' + CONVERT(VARCHAR(10), #cnt) + ']),'
SET #cnt+=1
END
SET #sql= LEFT(#sql, Len(#sql) - 1)
SET #sql+=') AS x([percent], [count])'
EXEC Sp_executesql
#sql
OUTPUT
pkTestInstanceID percent count
---------------- ------- -----
1 25 1
1 75 3
2 50 2
2 50 2
You don't really need to pivot here. You can do a UNION on the resultset as suggested by #bksi like below
select pkTestInstanceID, percent1 as [percent], count1 as count
from (
inner result set
) tab
UNION
select pkTestInstanceID, percent2, count2
from (
inner result set
) tab1
Related
List combination of numbers which have same sum
**N** is a prositive number Need list of scenarios which have sum equal N For example if N=4 ScenarioId Value ---------- ----- 1 1 1 1 1 1 1 1 2 2 2 1 2 1 3 2 3 2 4 3 4 1 5 4 above list is required. If you sum by ScenarioId all sum must equal to N UPDATE Here is my own solution. however, I am not sure about the multiplication of two different number sets would not be equal at any time. My current question is Is there any possibilities a + b + c = d + e + f and a * b * c = d * e * f Test link is here DECLARE #N int = 4; SELECT [Value] = CAST(number + 1 as tinyint) INTO #Values FROM master.dbo.spt_values WHERE number < #N AND [Type] = 'p' ;WITH COMBINATIONS AS( SELECT ScenarioKey = CAST(NULL AS nvarchar(MAX)), [Value], Total = 0, Multipication = 1, MemeberCount = 0 FROM #Values UNION ALL SELECT ScenarioKey = ISNULL(S.ScenarioKey, '') + IIF(S.ScenarioKey IS NULL, '', N'-') + CAST(P.[Value] AS nvarchar(10)), S.[Value], Total = S.Total + P.[Value], Multipication = S.Multipication * P.[Value], MemeberCount = MemeberCount + 1 FROM #Values P JOIN COMBINATIONS AS S ON S.Total < S.[Value] ), SCENARIOS AS( SELECT ScenarioKey ,ScenarioId = ROW_NUMBER() OVER(ORDER BY ScenarioKey) ,[Value] FROM ( SELECT ScenarioKey ,[Value] ,Multipication ,MemeberCount -- this will prevent dublications. because 1 * 2 * 3 = 3 * 2 * 1 -- however, I am not sure about multipication of two different number sets would not be equal any time ,RowNo = ROW_NUMBER() OVER(PARTITION BY [Value],Multipication,MemeberCount ORDER BY [Value],ScenarioKey) FROM COMBINATIONS WHERE Total = #N ) X WHERE RowNo = 1 AND [Value] = #N ) SELECT R.ScenarioId ,[Value] = S.[value] FROM SCENARIOS R CROSS APPLY (SELECT [value] FROM STRING_SPLIT(R.ScenarioKey, '-')) S DROP TABLE #Values
It's too long for comment, so I post this as an answer. I want to note, that this is a static example, but I hope it can be easily translated as a dynamic statement. Steps are written as comments in the statement: WITH rcte AS ( -- Recursive query to generate all numbers from 1 to 4 SELECT 0 AS Number UNION ALL SELECT Number + 1 FROM rcte WHERE Number < 4 ), permutations AS ( -- All possible permutations with sum equal to 4 -- There is additional column DuplicateMarker. -- It will be used later, because 0,0,0,4 and 0,4,0,0 are the same SELECT t1.Number AS Number1, t2.Number AS Number2, t3.Number AS Number3, t4.Number AS Number4, CONCAT(LTRIM(STR(t1.Number)), '.', LTRIM(STR(t2.Number)), '.', LTRIM(STR(t3.Number)), '.', LTRIM(STR(t4.Number))) AS DuplicateMarker FROM rcte t1, rcte t2, rcte t3, rcte t4 WHERE (t1.Number + t2.Number + t3.Number + t4.Number) = 4 ), duplicates AS ( -- Get data with splitted DuplicateMarker column SELECT * FROM permutations CROSS APPLY (SELECT [value] FROM STRING_SPLIT(DuplicateMarker, '.')) t ), results AS ( -- Get unique combinations -- WITHIN GROUP (ORDER BY) will order strings and 0.0.0.4 and 0.4.0.0 will be the same SELECT DISTINCT STRING_AGG([value], '.') WITHIN GROUP (ORDER BY [value]) AS ScenarioValue FROM duplicates GROUP BY Number1, Number2, Number3, Number4 ) SELECT DENSE_RANK() OVER (ORDER BY r.ScenarioValue) AS ScenarioID, s.[value] FROM results r CROSS APPLY (SELECT [value] FROM STRING_SPLIT(r.ScenarioValue, '.')) s WHERE [value] <> '0' Output: ScenarioID value 1 4 2 1 2 3 3 2 3 2 4 1 4 1 4 2 5 1 5 1 5 1 5 1 Update: Thanks to #AndriyM's comment, I've made some changes and now you can eliminate string manipulations: WITH rcte AS ( -- Recursive query to generate all numbers from 0 to 4 SELECT 0 AS Number UNION ALL SELECT Number + 1 FROM rcte WHERE Number < 4 ), combinations AS ( -- All different combinations with sum equal to 4 SELECT t1.Number AS Number1, t2.Number AS Number2, t3.Number AS Number3, t4.Number AS Number4, ROW_NUMBER() OVER (ORDER BY t1.Number, t2.Number, t3.Number, t4.NUmber) AS ScenarioID FROM rcte t1, rcte t2, rcte t3, rcte t4 WHERE ((t1.Number + t2.Number + t3.Number + t4.Number) = 4) AND (t1.Number <= t2.Number) AND (t2.Number <= t3.Number) AND (t3.Number <= t4.Number) ) SELECT c.ScenarioID, v.[value] FROM combinations c CROSS APPLY (VALUES (c.NUmber1), (c.Number2), (c.Number3), (c.Number4)) AS v ([value]) WHERE v.[value] > 0 Update 2: Approach using dynamic statement - probably not the best approach, but is based on statement from first update: -- Set your #n value DECLARE #n int SET #n = 4 -- Declarations DECLARE #combinationsSelect nvarchar(max) DECLARE #combinationsRowNumber nvarchar(max) DECLARE #combinationsFrom nvarchar(max) DECLARE #combinationsWhere1 nvarchar(max) DECLARE #combinationsWhere2 nvarchar(max) DECLARE #combinationsValues nvarchar(max) SET #combinationsSelect = N'' SET #combinationsRowNumber = N'' SET #combinationsFrom = N'' SET #combinationsValues = N'' SET #combinationsWhere1 = N'' SET #combinationsWhere2 = N'' -- Generate dynamic parts of the statement ;WITH numbers AS ( SELECT 1 AS Number UNION ALL SELECT Number + 1 FROM Numbers WHERE Number < #n ) SELECT #combinationsSelect = #combinationsSelect + N', t' + LTRIM(STR(Number)) + N'.Number AS Number' + LTRIM(STR(Number)), #combinationsRowNumber = #combinationsRowNumber + N', t' + LTRIM(STR(Number)) + N'.Number', #combinationsValues = #combinationsValues + N', (c.Number' + LTRIM(STR(Number)) + N')', #combinationsFrom = #combinationsFrom + N', rcte t' + LTRIM(STR(Number)), #combinationsWhere1 = #combinationsWhere1 + N'+ t' + LTRIM(STR(Number)) + N'.Number ', #combinationsWhere2 = #combinationsWhere2 + CASE WHEN Number = 1 THEN N'' ELSE N'AND (t' + LTRIM(STR(Number-1)) + N'.Number <= t' + + LTRIM(STR(Number)) + N'.Number) ' END FROM numbers SET #combinationsSelect = STUFF(#combinationsSelect, 1, 2, N'') SET #combinationsRowNumber = STUFF(#combinationsRowNumber, 1, 2, N'') SET #combinationsValues = STUFF(#combinationsValues, 1, 2, N'') SET #combinationsFrom = STUFF(#combinationsFrom, 1, 2, N'') SET #combinationsWhere1 = STUFF(#combinationsWhere1, 1, 2, N'') SET #combinationsWhere2 = STUFF(#combinationsWhere2, 1, 4, N'') -- Dynamic statement DECLARE #stm nvarchar(max) SET #stm = N'WITH rcte AS ( SELECT 0 AS Number UNION ALL SELECT Number + 1 FROM rcte WHERE Number < ' + LTRIM(STR(#n)) + N'), combinations AS ( SELECT ' + #combinationsSelect + N', ROW_NUMBER() OVER (ORDER BY ' + #combinationsRowNumber + N') AS ScenarioID FROM ' + #combinationsFrom + N' WHERE ((' + #combinationsWhere1 + N') = ' + LTRIM(STR(#n)) + ') AND ' + #combinationsWhere2 + N') SELECT c.ScenarioID, v.[value] FROM combinations c CROSS APPLY (VALUES ' + #combinationsValues + N') AS v ([value]) WHERE v.[value] > 0' -- Execute dynamic statement EXEC (#stm)
If you have sample data like below You can write query like below Declare #N int =4 Select T.* From #T T cross apply ( select S, SUM(V) Total From #T Group By S) Totals Where Totals.Total=#N and T.S = Totals.S
Built DWH From Father-Child table efficiently with T-SQL
For the last two days, I've been trying to find an efficient solution as most dynamic as possible but I can't make it. Do you have a hint for the following example? I tried a recursive call to get the "level" or the native join so far with the results below. I have "initTable": parent | child -------+------ A | H A | B A | C B | D B | G C | F D | E I want to have "finalTable": (in the bescase with dynamically create columns "levelX" level1 | level2 | level 3 | level 4 -------+--------+---------+--------- A | A | A | H A | A | C | F A | A | B | G A | B | D | E Attempt #1: recursive way to get the level Question: Is there a possibility to create the for each level a column during the recursion? WITH recTable (father, child, lev) AS ( SELECT p1.father, p1.child, 0 as lev FROM initTable AS p1 WHERE p1.father = 'A' UNION ALL SELECT p1.father, p1.child, lev+1 FROM initTable AS p1 INNER JOIN recTable as p2 ON p1.father = p2.child ) SELECT * FROM ASD Attempt #2: but with "wrong" order Here I would need to fill up the columns "backwards" somehow... SELECT p1.child AS Level 1, p2.child AS Level 2, p3.child AS Level 3, p4.child AS Level 4 FROM initTable p1 LEFT JOIN initTable p2 ON p1.child = p2.father LEFT JOIN initTable p3 ON p2.child = p3.father LEFT JOIN initTable p4 ON p3.child = p4.father WHERE p1.father= 'A' Does someone know a nice and efficient way to solve this problem? I feel like I m pretty close but I just can't solve it so far.
The following is dynamic and will work for your example, as well as for any with more/less parent/child relationships: -- Get the number of required fields SELECT parent , child , 1 [level] INTO #checking FROM initTable WHERE parent NOT IN (SELECT child FROM initTable) ; WHILE EXISTS (SELECT * FROM #checking c JOIN initTable t ON c.child = t.parent) BEGIN INSERT INTO #checking SELECT t.parent , t.child , (SELECT MAX([level]) + 1 FROM #checking) FROM #checking c JOIN initTable t ON c.child = t.parent ; DELETE FROM #checking WHERE [level] <> (SELECT MAX([level]) FROM #checking) ; END ; DECLARE #requiredLevels int = (SELECT TOP 1 [level] + 1 FROM #checking) ; DROP TABLE #checking ; -- Build a dynamic statement for the SELECT fields DECLARE #fieldSQL varchar(1000) = '' , #fieldsN int = #requiredLevels ; WHILE #fieldsN > 0 BEGIN IF #fieldsN > 2 BEGIN DECLARE #coalesceFields varchar(1000) = '' , #coalesceN int = #fieldsN WHILE #coalesceN > 1 BEGIN IF #coalesceFields = '' SET #coalesceFields = 'L' + CAST(#coalesceN AS varchar) + '.parent' ELSE SET #coalesceFields = #coalesceFields + ', L' + CAST(#coalesceN AS varchar) + '.parent' ; SET #coalesceN = #coalesceN - 1 END SET #fieldSQL = #fieldSQL + ', COALESCE(' + #coalesceFields + ') [level ' + CAST(#requiredLevels - #fieldsN + 1 AS varchar) + ']' END ELSE SET #fieldSQL = #fieldSQL + ', L' + CAST(#fieldsN AS varchar) + '.' + CASE WHEN #fieldsN = 1 THEN 'child' ELSE 'parent' END + ' [level ' + CAST(#requiredLevels - #fieldsN + 1 AS varchar) + ']' ; SET #fieldsN = #fieldsN - 1 END SET #fieldSQL = SUBSTRING(#fieldSQL, 3, LEN(#fieldSQL) - 2) -- Build a dynamic statement for the LEFT JOINs DECLARE #joinSQL varchar(1000) = '' , #joinsN int = 2 WHILE #joinsN <= #requiredLevels BEGIN SET #joinSQL = #joinSQL + ' LEFT JOIN initTable L' + CAST(#joinsN AS varchar) + ' ON L' + CAST(#joinsN - 1 AS varchar) + '.' + CASE WHEN #joinsN = 2 THEN 'child' ELSE 'parent' END + ' = L' + CAST(#joinsN AS varchar) + '.child' SET #joinsN = #joinsN + 1 END -- Build the final SQL statement and execute DECLARE #SQL varchar(8000) = ' SELECT ' + #fieldSQL + ' FROM ( SELECT child FROM initTable WHERE child NOT IN (SELECT parent FROM initTable) ) L1' + #joinSQL EXEC (#SQL)
Convert Row to Column based on data in SQL
The below image is my table The below excel is the design for output. My table contains 12 columns for each month and an year column. An item, there it can be available in multiple years and data for each month. year- itemcode- jan- feb 2014- pqr- 12- 11 2015- pqr- 4- 8 I need to generated the below output. For an item available for multiple years output needs to list in the following manner. ItemCode- Jan14- Feb14- Mar14-... Dec14- Jan15- Feb15-... Dec15 pqr- 12- 11- 4- 8- How can I able to achieve this. I tried different methods after googling. But I am not able to get proper input for solving this. At present I am trying some solutions found in SO. It will be very helpful someone can give some inputs. Thanks in advance.
You'll need to use dymanic SQL... Basically assuming a table called #tbl (with a little bit of sample data - ive only done 3 months but extend to 12!) CREATE TABLE #tbl ([ItemCode] NVARCHAR(20), [Year] INT, Jan INT, Feb INT, Mar INT) INSERT #tbl ( ItemCode, Year, Jan, Feb, Mar ) VALUES ( 'pqr', 2014, 12, 11, 7 ), ( 'pqr', 2015, 4, 8, 0 ), ( 'xyz', 2015, 7, 1, 0 ), ( 'abc', 2013, 63, 23, 12 ), ( 'abc', 2015, 63, 23, 12 ) we want to generate a query that looks like SELECT tbase.ItemCode , ISNULL(t13.Jan,0) AS 'Jan-13', ISNULL(t13.Feb,0) AS 'Feb-13', ISNULL(t13.Mar,0) AS 'Mar-13' , ISNULL(t14.Jan,0) AS 'Jan-14', ISNULL(t14.Feb,0) AS 'Feb-14', ISNULL(t14.Mar,0) AS 'Mar-14' , ISNULL(t15.Jan,0) AS 'Jan-15', ISNULL(t15.Feb,0) AS 'Feb-15', ISNULL(t15.Mar,0) AS 'Mar-15' FROM (SELECT DISTINCT(ItemCode) AS ItemCode FROM #tbl) AS tbase LEFT JOIN (SELECT * FROM #tbl AS t13 WHERE YEAR = 2013) AS t13 ON t13.ItemCode = tbase.ItemCode LEFT JOIN (SELECT * FROM #tbl AS t14 WHERE YEAR = 2014) AS t14 ON t14.ItemCode = tbase.ItemCode LEFT JOIN (SELECT * FROM #tbl AS t15 WHERE YEAR = 2015) AS t15 ON t15.ItemCode = tbase.ItemCode And results like: ItemCode Jan-13 Feb-13 Mar-13 Jan-14 Feb-14 Mar-14 Jan-15 Feb-15 Mar-15 abc 63 23 12 0 0 0 63 23 12 pqr 0 0 0 12 11 7 4 8 0 xyz 0 0 0 0 0 0 7 1 0 As you can see from the query - the 2 things to buld up are the lines , ISNULL(t13.Jan,0)... and LEFT JOIN (SELECT ... we can do this by declaring 2 NVARCHAR(MAX) variables (one for the select, one for the from) and building them up inside a while loop while iterating through the available years. ie something like... DECLARE #select NVARCHAR(MAX); DECLARE #from NVARCHAR(MAX); DECLARE #years TABLE(yr INT); DECLARE #year INT; DECLARE #yearName NVARCHAR(2) INSERT #years SELECT DISTINCT [Year] FROM #tbl SELECT #year = MIN(yr) FROM #years SELECT #yearName = RIGHT(CAST(#year AS NVARCHAR(4)),2) SELECT #select = 'SELECT tbase.ItemCode' SELECT #from = 'FROM (SELECT DISTINCT(ItemCode) AS ItemCode FROM #tbl) AS tbase ' WHILE EXISTS (SELECT NULL FROM #years WHERE yr = #year) BEGIN SELECT #yearName = RIGHT(CAST(#year AS NVARCHAR(4)),2) SELECT #select = #select + CHAR(13) + CHAR(10) + ', ISNULL(t' + #yearName + '.Jan,0) AS [Jan-' + #yearName + '],' + ' ISNULL(t' + #yearName + '.Feb,0) AS [Feb-' + #yearName + '],'-- +9 more + ' ISNULL(t' + #yearName + '.Mar,0) AS [Mar-' + #yearName + '] ' SELECT #from = #from + CHAR(13) + CHAR(10) + 'LEFT JOIN (SELECT * FROM #tbl AS t' + #yearName + ' WHERE [Year] = ' + CAST(#year AS NVARCHAR(4)) + ') AS t' + #yearName + ' ON t' + #yearName + '.ItemCode = tbase.ItemCode ' SELECT #year = #year + 1 END DECLARE #sql NVARCHAR(MAX) SELECT #sql = #select + CHAR(13) + CHAR(10) + #from EXEC (#sql) All you need to do is extend this to the full 12 months and you're done! NB - I've assumed that there is at least 1 entry for every year. If you have a gap where there is a year in the middle of your range with no entries whatsoever you'd need to do a minor modification to the WHILE loop - ie WHILE #year <= (SELECT MAX(Year) FROM #years)
Suppose you have the following table : select 'AA' as ItemCode,2014 as year, 23 as Jan, 55 as Feb, 55 as Mar,565 as Apr,656 as May, 343 as Jun,54 as Jul,23 as Aug,66 as Sep,645 as Oct,32 as Nov,66 as Dec into dbo.test ; insert into dbo.test select 'AA',2015,554,456,3,54,756,98,2,765,24,876,34,66 union select 'BB',2014,45,56,3,54,756,98,2,765,24,876,34,66 union select 'BB',2015,45,56,3,54,756,98,2,765,24,876,34,66; With dynamic sql, do declare #sql nvarchar(1000); declare #sql2 nvarchar(1000); declare #year int; declare #first_year int; declare c cursor for select distinct year from dbo.test; open c; FETCH NEXT FROM c into #year if ##FETCH_STATUS = 0 begin select #sql='select test'+convert(varchar,#year)+'.ItemCode'; select #sql = #sql+',test'+CONVERT(varchar,#year)+'.Jan as Jan'+CONVERT(varchar,#year)+',test' +CONVERT(varchar,#year)+'.Feb as Feb'+CONVERT(varchar,#year)+',test' +CONVERT(varchar,#year)+'.Mar as Mar'+CONVERT(varchar,#year); select #sql2='test test'+CONVERT(varchar,#year); select #first_year=#year; end; FETCH NEXT FROM c into #year WHILE ##FETCH_STATUS = 0 begin select #sql = #sql+',test'+CONVERT(varchar,#year)+'.Jan as Jan'+CONVERT(varchar,#year)+',test' +CONVERT(varchar,#year)+'.Feb as Feb'+CONVERT(varchar,#year)+',test' +CONVERT(varchar,#year)+'.Mar as Mar'+CONVERT(varchar,#year); select #sql2=#sql2+' inner join test test'+CONVERT(varchar,#year)+' on test'+CONVERT(varchar,#year)+'.ItemCode=test'+CONVERT(varchar,#first_year)+'.ItemCode and test'+CONVERT(varchar,#year)+'.year='+CONVERT(varchar,#year); FETCH NEXT FROM c into #year end; close c; deallocate c; select #sql=#sql+' FROM '+#sql2 + ' AND test'+convert(varchar,#first_year)+'.year='+CONVERT(varchar,#year); print #sql EXECUTE sp_executesql #sql; Or, with standard SQL, something like this select test2014.ItemCode,test2014.Jan as Jan2014,test2014.Feb as Feb2014,test2015.Jan as Jan2015,test2015.Feb as Feb2015 from test test2014 inner join test test2015 on test2014.ItemCode=test2015.ItemCode where test2014.year=2014 and test2015.year=2015;
How to pivot in SQL SERVER [duplicate]
This question already has answers here: SQL Server: Examples of PIVOTing String data (7 answers) Closed 8 years ago. I have a table like this: HospitalName--- DRG--DrgCount K1 F67A 1 K1 F68A 1 K1 F69A 1 K1 F60A 1 K1 F61A 1 K2 F61A 1 I want to show this in SQL Server like this: HospitalName F67A F68A F69A F60A F61A K1 1 1 1 1 1 K2 0 0 0 0 1 I tried the code below : SELECT TOP 1000 HospitalCode,Durum,[A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z] FROM (SELECT * FROM TIGPatient) p PIVOT ( COUNT (DRG) FOR DRG IN ( [A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z]) ) AS pvt But in this code every DRG come with zero values. How can we do this with SQL Server?
just in place of [DRG] put [DRGCount] SELECT TOP 1000 HospitalCode,Durum,[A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z] FROM (SELECT * FROM TIGPatient) p PIVOT ( COUNT (DRGCount) FOR DRG IN ( [A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z]) ) AS pvt
This can be done using a Dynamic Crosstab. Read this article by Jeff Moden for reference: http://www.sqlservercentral.com/articles/Crosstab/65048 DECLARE #sql1 VARCHAR(2000) = '' DECLARE #sql2 VARCHAR(2000) = '' DECLARE #sql3 VARCHAR(2000) = '' SELECT #sql1 = 'SELECT HospitalName ' SELECT #sql2 = #sql2 + ' ,MAX(CASE WHEN DRG = ''' + DRG + ''' THEN DrgCount ELSE 0 END) AS [' + DRG + ']' + CHAR(10) FROM( SELECT DISTINCT DRG FROM temp )t ORDER BY DRG SELECT #sql3 = 'FROM temp GROUP BY HospitalName ORDER BY HospitalName' PRINT (#sql1 + #sql2 + #sql3) EXEC (#sql1 + #sql2 + #sql3)
SELECT [HospitalName], [F67A], [F68A], [F69A], [F60A], [F61A] FROM tbl PIVOT( COUNT([DRG]) FOR [DRG] IN ([F67A], [F68A], [F69A], [F60A], [F61A]) ) AS p SQLFiddle As for your query : Remove Durum field from the SELECT ; No need for a temporary table (SELECT * FROM TIGPatient) p; So the following should work : SELECT TOP 1000 HospitalCode ,[A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z] FROM TIGPatient PIVOT ( COUNT (DRG) FOR DRG IN([A01Z],[A03Z],[A05Z],[Z99A],[Z98A],[Z97A],[Z96A],[A06Z],[A07Z],[A08A],[A08B],[A09A],[A09B],[A40Z],[A41A],[A41B],[B01Z],[B02A],[B02B],[B02C],[B03A],[B03B],[B04A],[B04B],[B05Z],[B06A],[B06B],[B07A],[B07B],[B40Z],[B41Z],[B60A],[B60B],[B61A],[B61B],[B62Z],[B63Z],[B64A],[B64B],[B65Z],[B66A],[B66B],[B67A],[B67B],[B67C],[B68A],[B68B],[B69A],[B69B],[B70A],[B70B],[B70C],[B70D],[B71A],[B71B],[B72A],[B72B],[B73Z],[B74Z],[B75Z],[B76A],[B76B],[B77Z],[B78A],[B78B],[B79Z],[B80Z],[B81A],[B81B],[C01Z],[C02Z],[C03Z],[C04Z],[C05Z],[C10Z],[C11Z],[C12Z],[C13Z],[C14Z],[C15A],[C15B],[C16A],[C16B],[C60A],[C60B],[C61Z],[C62Z],[C63A],[C63B],[D01Z],[D02A],[D02B],[D02C],[D03Z],[D04A],[D04B],[D05Z],[D06Z],[D09Z],[D10Z],[D11Z],[D12Z],[D13Z],[D14Z],[D40Z],[D60A],[D60B],[D61Z],[D62Z],[D63A],[D63B],[D64Z],[D65Z],[D66A],[D66B],[D67A],[D67B],[E01A],[E01B],[E02A],[E02B],[E02C],[E40Z],[E41Z],[E60A],[E60B],[E61A],[E61B],[E62A],[E62B],[E62C],[E63Z],[E64Z],[E65A],[E65B],[E66A],[E66B],[E66C],[E67A],[E67B],[E68Z],[E69A],[E69B],[E69C],[E70A],[E70B],[E71A],[E71B],[E71C],[E72Z],[E73A],[E73B],[E73C],[E74A],[E74B],[E74C],[E75A],[E75B],[E75C],[F01A],[F01B],[F02Z],[F03Z],[F04A],[F04B],[F05A],[F05B],[F06A],[F06B],[F07A],[F07B],[F08A],[F08B],[F09A],[F09B],[F10Z],[F11A],[F11B],[F12Z],[F13Z],[F14A],[F14B],[F14C],[F15Z],[F16Z],[F17Z],[F18Z],[F19Z],[F20Z],[F21A],[F21B],[F40Z],[F41A],[F41B],[F42A],[F42B],[F60A],[F60B],[F60C],[F61Z],[F62A],[F62B],[F63A],[F63B],[F64Z],[F65A],[F65B],[F66A],[F66B],[F67A],[F67B],[F68Z],[F69A],[F69B],[F70A],[F70B],[F71A],[F71B],[F72A],[F72B],[F73A],[F73B],[F74Z],[F75A],[F75B],[F75C],[G01A],[G01B],[G02A],[G02B],[G03A],[G03B],[G03C],[G04A],[G04B],[G04C],[G05A],[G05B],[G06Z],[G07A],[G07B],[G08A],[G08B],[G09Z],[G10Z],[G11A],[G11B],[G12A],[G12B],[G42A],[G42B],[G43Z],[G44A],[G44B],[G44C],[G45A],[G45B],[G46A],[G46B],[G46C],[G60A],[G60B],[G61A],[G61B],[G62Z],[G63Z],[G64Z],[G65A],[G65B],[G66A],[G66B],[G67A],[G67B],[G68A],[G68B],[G69Z],[G70A],[G70B],[H01A],[H01B],[H02A],[H02B],[H02C],[H05A],[H05B],[H06Z],[H07A],[H07B],[H08A],[H08B],[H40Z],[H41A],[H41B],[H42A],[H42B],[H42C],[H60A],[H60B],[H60C],[H61A],[H61B],[H62A],[H62B],[H63A],[H63B],[H64A],[H64B],[I01Z],[I02A],[I02B],[I03A],[I03B],[I03C],[I04Z],[I05Z],[I06Z],[I07Z],[I08A],[I08B],[I09A],[I09B],[I10A],[I10B],[I11Z],[I12A],[I12B],[I12C],[I13A],[I13B],[I13C],[I14Z],[I15Z],[I16Z],[I17Z],[I18Z],[I19Z],[I20Z],[I21Z],[I23Z],[I24Z],[I25Z],[I27A],[I27B],[I28A],[I28B],[I29Z],[I30Z],[I60Z],[I61Z],[I63Z],[I64A],[I64B],[I65A],[I65B],[I66A],[I66B],[I67A],[I67B],[I68A],[I68B],[I68C],[I69A],[I69B],[I69C],[I70Z],[I71A],[I71B],[I71C],[I72A],[I72B],[I73A],[I73B],[I73C],[I74A],[I74B],[I74C],[I75A],[I75B],[I75C],[I76A],[I76B],[I76C],[I77A],[I77B],[I78A],[I78B],[J01Z],[J06A],[J06B],[J07A],[J07B],[J08A],[J08B],[J09Z],[J10Z],[J11Z],[J12A],[J12B],[J12C],[J13A],[J13B],[J14Z],[J60A],[J60B],[J62A],[J62B],[J63Z],[J64A],[J64B],[J65A],[J65B],[J67A],[J67B],[J68A],[J68B],[K01Z],[K02Z],[K03Z],[K04Z],[K05Z],[K06Z],[K07Z],[K08Z],[K09Z],[K40Z],[K60A],[K60B],[K61Z],[K62A],[K62B],[K62C],[K63Z],[K64A],[K64B],[L02A],[L02B],[L03A],[L03B],[L04A],[L04B],[L04C],[L05A],[L05B],[L06A],[L06B],[L07A],[L07B],[L08A],[L08B],[L09A],[L09B],[L09C],[L40Z],[L41Z],[L42Z],[L60A],[L60B],[L60C],[L61Z],[L62A],[L62B],[L63A],[L63B],[L63C],[L64Z],[L65A],[L65B],[L66Z],[L67A],[L67B],[L67C],[M01Z],[M02A],[M02B],[M03A],[M03B],[M04A],[M04B],[M05Z],[M06A],[M06B],[M40Z],[M60A],[M60B],[M61A],[M61B],[M62A],[M62B],[M63Z],[M64Z],[N01Z],[N02A],[N02B],[N03A],[N03B],[N04Z],[N05A],[N05B],[N06Z],[N07Z],[N08Z],[N09Z],[N10Z],[N11A],[N11B],[N60A],[N60B],[N61Z],[N62A],[N62B],[O01A],[O01B],[O01C],[O02A],[O02B],[O03Z],[O04Z],[O05Z],[O60A],[O60B],[O60C],[O61Z],[O63Z],[O64A],[O64B],[O66A],[O66B],[P01Z],[P02Z],[P03Z],[P04Z],[P05Z],[P06A],[P06B],[P60A],[P60B],[P61Z],[P62Z],[P63Z],[P64Z],[P65A],[P65B],[P65C],[P65D],[P66A],[P66B],[P66C],[P66D],[P67A],[P67B],[P67C],[P67D],[Q01Z],[Q02A],[Q02B],[Q60A],[Q60B],[Q60C],[Q61A],[Q61B],[Q61C],[Q62Z],[R01A],[R01B],[R02A],[R02B],[R03A],[R03B],[R04A],[R04B],[R60A],[R60B],[R60C],[R61A],[R61B],[R61C],[R62A],[R62B],[R63Z],[R64Z],[S60Z],[S65A],[S65B],[S65C],[T01A],[T01B],[T01C],[T60A],[T60B],[T61A],[T61B],[T62A],[T62B],[T63A],[T63B],[T64A],[T64B],[U40Z],[U60Z],[U61A],[U61B],[U62A],[U62B],[U63A],[U63B],[U64Z],[U65Z],[U66Z],[U67Z],[U68Z],[V60A],[V60B],[V61Z],[V62A],[V62B],[V63A],[V63B],[V64Z],[W01Z],[W02Z],[W03Z],[W04Z],[W60Z],[W61Z],[X02Z],[X04A],[X04B],[X05Z],[X06A],[X06B],[X07A],[X07B],[X60A],[X60B],[X60C],[X61Z],[X62A],[X62B],[X63A],[X63B],[X64A],[X64B],[Y01Z],[Y02A],[Y02B],[Y03Z],[Y60Z],[Y61Z],[Y62A],[Y62B],[Z01A],[Z01B],[Z40Z],[Z60A],[Z60B],[Z60C],[Z61Z],[Z62Z],[Z63A],[Z63B],[Z64A],[Z64B],[Z65Z],[901Z],[902Z],[903Z],[960Z],[961Z],[963Z]) ) AS p
n to n relationship how to obtain a result in one row
so I have an employee that can work in many companies so I have an n to n relationship, how can I obtain the companies that one employee works in, in just one row with sql? example table - employee Employeeid employeename 1 mike table company companyId CompanyName 1 cocacola 2 nokia 3 intel table employeeCompany id employeeid companyid 1 1 1 2 1 2 3 1 3 I thought with this but canĀ“t select Employeeid , companyid from employeeCompany where employeeid = 1 group by Employeeid , companyid
Easiest way to do it in Sql Server is by use of FOR XML PATH. The cryptic part .value('text()[1]','nvarchar(max)') handles special xml characters. select employee.*, companies.* from Employee OUTER APPLY ( select stuff ((SELECT ', ' + Company.CompanyName FROM EmployeeCompany INNER JOIN Company ON EmployeeCompany.CompanyId = Company.CompanyID WHERE EmployeeCompany.employeeid = Employee.EmployeeID ORDER BY Company.CompanyName FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)') , 1, 2, '') Companies ) companies See demo at Sql Fiddle.
It sounds like you want something that is similar to mySQL's Group_Concat in SQL Server? If you are looking for a way to do this so that each companyid is in a separate column, then that would only be possible with some difficulty using dynamic SQL. At which time it might be easier to just return this to an application and let it handle what it needs within its own logic? BTW, the dynamic SQL logic would go something like this in case you were wondering...notice how nasty it is...thus why I would suggest against it. select #highestCount = max(count(*)) from employeeCompany group by Employeeid declare createtemptable varchar(max), #filltableselect varchar(max), #filltablejoin varchar(max) declare #currentCount int set #currentCount = 0 set #createtemptable = 'CREATE TABLE #Temp (EmployeeID INT' set #filltableselect = 'INSERT INTO #Temp SELECT EmployeeCompany0.EmployeeID, EmployeeCompany0.CompanyID' set #filltablejoin = 'FROM EmployeeCompany AS EmployeeCompany0' while(#currentCount < #highestCount) begin set #createtemptable = #createtemptable + ', CompanyID' + CAST(#currentCount AS VARCHAR(2)) + ' INT' if(#currentCount > 0) begin set #filltableselect = #filltableselect + ', EmployeeCompany' + CAST(#currentCount AS VARCHAR(2)) + '.CompanyId' set #filltablejoin = #filltablejoin + 'LEFT JOIN EmployeeCompany AS EmployeeCompany' + CAST(#currentCount AS VARCHAR(2)) + ' ON EmployeeCompany0.EmployeeID = EmployeeCompany' + CAST(#currentCount AS VARCHAR(2)) + '.EmployeeID' end set #currentCount = #currentCount + 1 end set #createtemptable = #createtemptable + ')' --This next line can be whatever you need it to be set #filltablejoin = #filltablejoin + 'WHERE employeeCompany0.EmployeeID = 1' exec #createtemptable exec #filltableselect + #filltablejoin