Sql语法拼图中的动态枢轴

时间:2015-07-12 17:34:33

标签: sql-server pivot

我有一张表如下。表#temp

Product     Date      1st Pass Count    2nd Pass Count   3rd Pass Count
A           06-07-2015       2               4              5
A           06-07-2015       3               2              1
B           06-07-2015       1               1              1

现在我想要一个如下视图;

Product      06-07-2015   07-07-2015    08-07-2015
    A            17          0             0
    B            3           0             0

日期列是第1次,第2次和第3次传递的总和。

我已经尝试过以下查询。我需要帮助的2个问题。

问题1 - 产品A的多行。 问题2 - 似乎在使用pivot的sql查询中添加了所有第1,第2和第3遍。尝试总和([第一遍] + [第二遍] + [第三遍]),它给出了语法错误。

在我尝试纠正上述两个问题之前,当前的代码有效。

DECLARE @cols as NVARCHAR(MAX)
DECLARE @query as NVARCHAR(MAX)

Select @cols=STUFF ( SELECT ',' +QUOTENAME(PRODUCT) FROM #TEMP group by DATE ORDER BY DATE FOR XML PATH (''), TYPE).value.('.',NVARCHAR(MAX)'),1,1,'') set @query='SELECT [PRODUCT],' + @cols + 'from 'Select [PRODUCT],[DATE],[1st Pass],[2nd Pass],[3rd Pass] from #TEMP)x Pivot (sum [1st pass] FOR DTE in ('+@cols+') )p' execute (@query)

在解决最后两个问题方面,我是否遗漏了一些明显的东西?

1 个答案:

答案 0 :(得分:0)

我们可以使用Pivot和Cross Apply

来获得上述结果集

普通数据透视

DECLARE @t  TABLE  (Product Varchar(5),dated varchar(10),firstcount int,secondcount int,thirdcpount int)

INSERT INTO @t (Product,dated,firstcount,secondcount,thirdcpount)values 
 ('A','06-07-2015',2,4,5),
 ('A','06-07-2015',3,2,1),
 ('B','06-07-2015',1,1,1)

select Product,SUM(ISNULL([06-07-2015],0)) As [06-07-2015],SUM(ISNULL([07-07-2015],0))As [07-07-2015],SUM(ISNULL([08-07-2015],0))As [08-07-2015] from (
select Product,dated,COL,val from @t
CROSS APPLY (VALUES('firstcount',firstcount),('secondcount',secondcount),('thirdcpount',thirdcpount))CS(COL,val))TT
PIVOT (SUM(VAL) FOR Dated IN ([06-07-2015],[07-07-2015],[08-07-2015]))T
GROUP BY Product

并且

使用Dynamic Query Pivot

IF OBJECT_ID('tempdb..#t') IS NOT NULL
 DROP TABLE #t
GO
CREATE TABLE #t (Product Varchar(5),dated varchar(10),firstcount int,secondcount int,thirdcpount int)

INSERT INTO #t (Product,dated,firstcount,secondcount,thirdcpount)values 
 ('A','06-07-2015',2,4,5),
 ('A','06-07-2015',3,2,1),
 ('B','06-07-2015',1,1,1)
,('A','07-07-2015',2,11,5),
('A','07-07-2015',3,2,1),
('B','07-07-2015',1,1,1)
,('A','08-07-2015',3,11,6),
('A','08-07-2015',1,6,1),
('B','08-07-2015',11,1,6)


DECLARE @statement NVARCHAR(max)
,@columns NVARCHAR(max)

SELECT @columns = ISNULL(@columns + ', ', '') + N'[' + tbl.dated + ']'
FROM (
   SELECT DISTINCT dated
   FROM #t
   ) AS tbl

SELECT @statement = ' select Product,SUM(ISNULL([06-07-2015],0)) As [06-07-2015],SUM(ISNULL([07-07-2015],0))As [07-07-2015],SUM(ISNULL([08-07-2015],0))As [08-07-2015] from (
select Product,dated,COL,val from #t
CROSS APPLY (VALUES(''firstcount'',firstcount),(''secondcount'',secondcount),(''thirdcpount'',thirdcpount))CS(COL,val))TT
PIVOT (SUM(VAL) FOR Dated IN (' + @columns + ')) as pvt GROUP BY Product'

EXEC sp_executesql @statement = @statement