首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

sql列转行 !

2013-08-16 
sql列转行在线等!急急急如何将图1做成图2这样 (sum的时候是按Quname分组求和的)在线等!QQ:1197547385日期

sql列转行 在线等!急急急
sql列转行  !
如何将图1做成图2这样 (sum的时候是按Quname分组求和的)在线等!QQ:1197547385 日期咋弄成动态的
--拼SQL
DECLARE @sql NVARCHAR(MAX), @datelist NVARCHAR(MAX)
SELECT @datelist = STUFF((SELECT DISTINCT ','+QUOTENAME([date]) FROM #temp FOR XML PATH('')),1,1,'')--日期动态
SET @sql = N'
SELECT * FROM
(
    SELECT Quname, [Date],
        [SUM(newchongzhiacct)] = CAST(SUM(newchongzhiacct) AS DECIMAL(10, 2)),
        [SUM(todaychongzhi)] = CAST(SUM(todaychongzhi) AS DECIMAL(10, 2)),
        [SUM(newaddxiaofeiacct)] = CAST(SUM(newaddxiaofeiacct) AS DECIMAL(10, 2)),
        [SUM(sevenleijixiaofeiacct)] = CAST(SUM(sevenleijixiaofeiacct) AS DECIMAL(10, 2)),
        [SUM(sevenhuoyueacct)] = CAST(SUM(sevenhuoyueacct) AS DECIMAL(10, 2)),
        [SUM(sevenleijixiaofeiacct)/SUM(sevenhuoyueacct)] = CAST((CASE WHEN SUM(sevenhuoyueacct) = 0 THEN 0 ELSE SUM(sevenleijixiaofeiacct)/SUM(sevenhuoyueacct) end) AS DECIMAL(10, 2)),
        [SUM(todayxiaofei)] = CAST(SUM(todayxiaofei) AS DECIMAL(10, 2)),
        [SUM(todayxiaofeiacctnum)] = CAST(SUM(todayxiaofeiacctnum) AS DECIMAL(10, 2)),


        [SUM(todayxiaofei)/SUM(todayxiaofeiacctnum)] = CAST((CASE WHEN SUM(todayxiaofeiacctnum) = 0 THEN 0 ELSE SUM(todayxiaofei)/SUM(todayxiaofeiacctnum)END)  AS DECIMAL(10, 2))
    FROM #temp T
    --WHERE Quname = ''支付宝快充''  --根据你给出的显示结果,一次只能显示一个商城的报表
    GROUP BY Quname, [Date]
) A
UNPIVOT
(xx FOR yy IN([SUM(newchongzhiacct)], [SUM(todaychongzhi)], [SUM(newaddxiaofeiacct)], [SUM(sevenleijixiaofeiacct)],[SUM(sevenhuoyueacct)],[SUM(sevenleijixiaofeiacct)/SUM(sevenhuoyueacct)],[SUM(todayxiaofei)],[SUM(todayxiaofeiacctnum)],[SUM(todayxiaofei)/SUM(todayxiaofeiacctnum)])) b
PIVOT
(MAX(xx) FOR [Date] IN('+ @datelist +')) c  
ORDER BY Quname
'
--PRINT @sql
EXEC(@sql)

 

热点排行