小编典典

多列的 SQL 多个 WHERE 条件

sql

我正在尝试创建下表:

ID Name SalesDate MaxNikeSales MaxAdidasSales SalesDifference (Nike - Adidas)
1 John 2022-01-01 94343 23453 70890
2 John 2022-01-02 23456 0 23456
3 John 2022-01-03 54678 0 54678
4 John 2022-01-04 12310 43345 -31035
5 John 2022-01-05 0 94575 -94575

我正在尝试使用 WHERE 子句创建表,但不确定如何让两个品牌在同一个表中显示为字段。

我正在使用的数据结构如下:

Name Brand Sales SalesDate
John Nike 13344 2022-01-01
John Adidas 23453 2022-01-01
John Nike 94343 2022-01-01
John Nike 23456 2022-01-02
John Nike 54678 2022-01-03
John Nike 23643 2022-01-03
John Nike 12310 2022-01-04
John Adidas 43345 2022-01-04
John Adidas 94575 2022-01-05
John Adidas 23451 2022-01-05

我非常感谢您对此提供的任何帮助。


阅读 137

收藏
2022-07-21

共1个答案

小编典典

您可以将 max() 与 case 子句一起使用来计算您需要的内容。按 SalesDate 对数据进行分组,您就拥有了所需的一切。

select row_number() over(order by SalesDate) as ID
       , max(Name)
       , SalesDate
       , max(case when Brand = 'Nike' then Sales else 0 end) MaxNikeSales
       , max(case when Brand = 'Adidas' then Sales else 0 end) MaxAdidasSales
       , max(case when Brand = 'Nike' then Sales else 0 end) - 
         max(case when Brand = 'Adidas' then Sales else 0 end) 
         as "SalesDifference (Nike - Adidas)"
from mytable
group by SalesDate

这是一个演示

2022-07-21