用于显示数据透视的SQL

时间:2018-06-01 00:21:21

标签: sql sql-server

我有下表: enter image description here

我希望显示以下输出:

enter image description here

以上基本上是每天的(quan * cst)。现在我可以通过以下sql来解决这个问题:

   select  t1.pid, isnull(b.m1,0) as day1sale, isnull(a.m2,0) as day2sale
 from dbo.test1 t1
 left join(select pid, sum(quan*cst) m1
 from dbo.test1  where date='2017-05-01' group by pid) b on b.pid=t1.pid 
 left join (select pid, sum(quan*cst) m2
 from dbo.test1  where date='2017-05-02' group by pid) a on a.pid=t1.pid 
 group by t1.pid,m2 ,m1
 order by t1.pid

但是我想知道是否有一种更简单的方法可以做到这一点而不需要对日期进行硬编码?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

使用自联接获取不同日期的列表,可以旋转结果集并将所需的聚合应用于每个PID。

CREATE TABLE #TEMP_EXAMPLE
(
[DATE] DATE,
[ID] INT,
[PID] INT,
[QUAN] INT,
[CST] INT
)

INSERT INTO #TEMP_EXAMPLE VALUES('05/01/2017','1','1','2','3')
INSERT INTO #TEMP_EXAMPLE VALUES('05/01/2017','2','2','6','2')
INSERT INTO #TEMP_EXAMPLE VALUES('05/01/2017','3','3','5','1')
INSERT INTO #TEMP_EXAMPLE VALUES('05/01/2017','4','1','1','3')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','5','3','3','1')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','6','4','4','7')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','7','1','7','3')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','8','5','2','8')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','9','6','5','6')
INSERT INTO #TEMP_EXAMPLE VALUES('05/02/2017','10','2','8','2')


SELECT ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY [DATE]) AS ID,*
INTO #TEMP_DYNAMIC_DATES
FROM (SELECT DISTINCT [DATE] FROM #TEMP_EXAMPLE ) AS X

SELECT * FROM #TEMP_DYNAMIC_DATES

SELECT PID,ISNULL(DAY1SALE,0) AS DAY1SALE,ISNULL(DAY2SALE,0) AS DAY2SALE FROM (
SELECT PID,SUM([QUAN] * [CST]) AS X, INDIC FROM (
SELECT A.*,
CASE WHEN B.ID = 1 THEN 'DAY1SALE'
     WHEN B.ID = 2 THEN 'DAY2SALE'
     END AS INDIC 
     FROM #TEMP_EXAMPLE AS A 
JOIN #TEMP_DYNAMIC_DATES AS B
ON A.DATE = B.DATE
) AS X
GROUP BY PID,INDIC) AS O
PIVOT(SUM(X) FOR INDIC IN([DAY1SALE],[DAY2SALE])) AS PT

enter image description here