日期:2014-05-17 浏览次数:20536 次
--PIVOT的一般语法是:PIVOT(聚合函数(列) FOR 列 in (…) )AS P
--
--完整语法:
--table_source
--PIVOT(
--聚合函数(value_column)
--FOR pivot_column
--IN(<column_list>)
--)
--eg.
--静态SQL(要求已知列名)
DECLARE @TB TABLE(ID INT ,VALUE1 NVARCHAR(50),VALUE2 NVARCHAR(50))
INSERT INTO @TB
SELECT 1,'A','S1' UNION ALL
SELECT 1,'B','S2' UNION ALL
SELECT 1,'C','S3' UNION ALL
SELECT 2,'A','S1' UNION ALL
SELECT 2,'B','S2' UNION ALL
SELECT 2,'C','S3'
SELECT * FROM (SELECT * FROM @TB) A
PIVOT (
MAX(VALUE2) FOR VALUE1 IN (A,B,C)--但这里写死了列名
) B
--eg.2
--动态SQL(由于用到字符串,因此表变量无法使用,改用临时表)
--DROP TABLE #TB
SELECT * INTO #TB FROM (
SELECT 1 id,'A' Value1,'S1' Value2 UNION ALL
SELECT 1,'B','S2' UNION ALL
SELECT 1,'C','S3' UNION ALL
SELECT 2,'A','S1' UNION ALL
SELECT 2,'B','S2' UNION ALL
SELECT 2,'C','S3')A
DECLARE @SQL VARCHAR(MAX)
SELECT @SQL = ISNULL(@SQL + '],[' , '') + Value1 from #TB GROUP BY Value1
SET @SQL = '[' + @SQL + ']'
EXEC ('SELECT * FROM (SELECT * FROM #TB) D PIVOT (MAX(VALUE2) FOR VALUE1 IN ('+@SQL+')) B')
--楼主没给 每日销售表?
--假如每日销售表就是图片中的上半部分的话,那么下半部分的统计参考如下:
SELECT
[第一周] = SUM(CASE WHEN DAY(日期) BETWEEN 1 AND 7 THEN 销售金额 END),
[第二周] = SUM(CASE WHEN DAY(日期) BETWEEN 8 AND 14 THEN 销售金额 END),
[第三周] = SUM(CASE WHEN DAY(日期) BETWEEN 15 AND 21 THEN 销售金额 END),
[第四周] = SUM(CASE WHEN DAY(日期) BETWEEN 22 AND 28 THEN 销售金额 END),
[第五周] = SUM(CASE WHEN DAY(日期) BETWEEN 29 AND 31 THEN 销售金额 END),
[最高业绩] = MAX(销售金额),
[最低业绩] = ISNULL(MIN(销售金额), 0),
[超3千天数]&