在sql中查找两个枢轴列之间的区别

时间:2019-12-25 06:28:13

标签: sql sql-server pivot

select count(*) AS id_CNT, Date, price
from table
where Date in ('2019-12-18', '2019-12-19')
  and Id = '-3'
group by Date, price
pivot
    (max(price) for date in (['2019-12-18'], ['2019-12-19']) piv)

我已经尝试过此脚本,但是下一步是什么,以便在此处显示所需的输出:

image contains data how it looks and what is the excepted result

2 个答案:

答案 0 :(得分:0)

  • 使您的主查询嵌套并为其别名(t
  • 删除引号,并在日期文字上保留方括号以创建列名
  • 假设ID是整数值,也请删除ID = '-3'的引号
  • 使用Date in ('2019-12-18', '2019-12-19')是多余的,因此请摆脱 其中

  • 枢轴部分的别名应在括号后

因此,请使用以下查询:

    SELECT piv.*, [2019-12-19] - [2019-12-18] as Diff 
      FROM
      (
       SELECT ID, Date, Price, COUNT(*) AS ID_Cnt
         FROM tab
        WHERE ID = -3
        GROUP BY ID, Date, price   
      ) t
      PIVOT
      (
       MAX(Price) for Date in ( [2019-12-18], [2019-12-19] )
      ) piv

Demo

从查询格式开始,其中包含in运算符后的文字方括号,我假设您的DBMS是 SQL-Server

答案 1 :(得分:0)

当只有2个日期时,您真的不需要先PIVOT然后再UNPIVOT来获得最终结果。

样本数据:

create table YourTable
(
  Id int not null,
  [Date] date not null,
  price decimal(16,2) not null
)

insert into YourTable
(id, [date], price) values
(-3, '2019-12-18', 94416.68),
(-3, '2019-12-19', 31352.26);

查询:

WITH CTE_DATA AS
(
  SELECT Id, [Date]
  , id_count = COUNT(*)
  , price = SUM(price)
  , rn = ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Date] DESC)
  FROM YourTable
  WHERE Id = -3
  AND [Date] IN ('2019-12-18', '2019-12-19')
  GROUP BY Id, [Date]
)
SELECT [Date], Id
, CAST(id_count AS VARCHAR(30)) AS id_count
, price
FROM CTE_DATA
UNION ALL
SELECT null, null, 'Result'
, (MAX(CASE WHEN rn=1 THEN price END) 
 - MAX(CASE WHEN rn=2 THEN price END))
FROM CTE_DATA
GROUP BY Id
ORDER BY Id desc, [Date]
GO
Date                |   Id | id_count | price    
:------------------ | ---: | :------- | :--------
18/12/2019 00:00:00 |   -3 | 1        | 94416.68 
19/12/2019 00:00:00 |   -3 | 1        | 31352.26 
null                | null | Result   | -63064.42

db <>提琴here