从SQL视图到gridview的聚合结果

时间:2013-04-17 22:57:31

标签: c# sql linq linq-to-sql gridview

我有来自多表的视图

ACCOUNT_NAME .......奖金..........值

customer1表............甲............ 14000

customer1表............乙............ 500

customer1表............Ç............ 14500

的customer2 ............甲............ 20000

的customer2 ............乙............ 200

的customer2 ............Ç............ 20200

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

如何检索此视图并使用LINQ

在GridView上显示此视图

...................甲.........乙..........ç

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

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

enter image description here

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我使用带动态的Pivots解决了我的问题,因为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)