2014-04-01 219 views
-2

我不肯定這可能我沒有這個想法我的表:tbcheckedSQL查詢和group by

[id] [name] [status] 

001 john  present 
001 john  present 
001 john  absent 
001 john  absent 
001 john  leave 
001 john  present 
001 john  present 
002 ace  present 
002 ace  absent 
002 ace  leave 

...

這是可能的嗎?在gridview1中輸出如何查詢? 1-7不在一週我想指望在1到XXX

[id] [name] [1]  [2]  [3]  [4]    [5]   [6]  [7] 

001 john present present absent absent   leave   present present 
002 ace present absent leave ... 
+4

旋轉和動態查詢。爲什麼你想要7列?他們如何投影。 –

+0

你有一個主鍵嗎?一個表本質上是無序的。 – Mihai

+0

這個問題很難理解!請解釋更多。 – mok

回答

0

你可以像這樣

DECLARE @TABLE TABLE 
( 
ID INT, 
STATUS VARCHAR(10) 
) 

INSERT INTO @TABLE 
VALUES (1, 'present'), 
     (1, 'present'), 
     (1, 'absent'), 
     (1, 'absent'), 
     (1, 'leave'), 
     (1, 'present'), 
     (1, 'present'), 
     (2, 'present'), 
     (2, 'absent'), 
     (2, 'leave') 


SELECT T1.ID, 
     STUFF( 
     ( 
     SELECT ',' + T2.STATUS 
     FROM @TABLE T2 
     WHERE T1.ID = T2.ID 
     FOR XML PATH ('') 
     ),1,1,'') 
FROM @TABLE T1 
GROUP BY T1.ID 

嘗試,否則你可以使用遊標進行循環Declare Cursor

0

如果你只有7行的ID,那麼這可能是有用的。 如果ID是任何隨機數,那麼你必須去 動態sql或過程如果可能的話。

select ID, 

SUBSTRING_INDEX(status,',','1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','2'),',','-1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','3'),',','-1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','4'),',','-1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','5'),',','-1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','6'),',','-1'), 

SUBSTRING_INDEX(SUBSTRING_INDEX(status,',','7'),',','-1') 

from 
(

SELECT ID, group_concat(status) as status 

FROM TABLE T 

GROUP BY ID 

) A