2013-04-17 87 views
0

我有這種說法從多表聚集結果的GridView

ACCOUNT_NAME .......獎金..........值

customer1表.... ........ A ............ 14000

customer1 ............ B .......... ..500

customer1表............ç............ 14500

的customer2 ........... .A ............ 20000

customer2 ............ B ............ 200

customer2 ............ C。 ........... 20200

http://im33.gulfup.com/Nt0mM.png

我怎麼能查找這個視圖,並顯示在GridView控件使用LINQ

由此看來.......... ......... A ......... B .......... C

customer1 ....... 14000 ...... .500 ....... 14500

的customer2 ....... 20000 ....... 200 ....... 20200

enter image description here

回答

1
SELECT account_name, 
SUM(CASE WHEN bonus = 'A' THEN value ELSE 0 END) AS A, 
SUM(CASE WHEN bonus = 'B' THEN value ELSE 0 END) AS B, 
SUM(CASE WHEN bonus = 'C' THEN value ELSE 0 END) AS C 
FROM YouView 
GROUP BY account_name 
+0

如果SQL可以更好地處理SQL – realnumber3012

+0

thankx,但是如果我擁有超過(A,B,C)獎金的獎勵,我該如何做到這一點。我的意思是我有其中列的獎金錶:獎金,值 – Fadi

+1

然後你可以看在樞軸的方向,UNPIVOT – realnumber3012

1

我解決了使用支點與動態的realnumber3012我的問題建議...

的證明表而這個鏈接

enter image description here

上的結果
DECLARE @cols NVARCHAR(2000) 
SELECT @cols = COALESCE(@cols + ',[' + bounse_name+ ']','[' + bounse_name + ']') 
FROM dbo.tbl_bounse 
DECLARE @query NVARCHAR(4000) 
SET @query = N'SELECT account_name , '+ @cols +' 
FROM 
(SELECT  tbl_account.account_name, tbl_account.account_career,  
      tbl_bounse.bounse_name, tbl_detail.detail_value 
FROM   tbl_account INNER JOIN 
tbl_detail ON tbl_account.account_id = tbl_detail.detail_accound_id 
INNER JOIN 
tbl_bounse ON tbl_detail.detail_bounce_id = tbl_bounse.bounse_id      
        ) p 
PIVOT 
(
MAX([detail_value]) 
FOR bounse_name IN 
('+ 
@cols +') 
) AS pvt;' 

EXECUTE(@query)