我有一张产品销售表,可能如下所示:
product | amount | ptype | pdate
p1 | 1.00 | sale | 01/01
p1 | 2.00 | base | 01/02
p2 | 1.50 | sale | 02/03
p3 | 5.25 | base | 10/10
我想建立一个表格,每行显示一个产品,金额的总和,如果产品是唯一的,则显示类型,否则将类型显示为“VAR”,如果产品是唯一的,则显示日期,否则显示日期作为NULL。因此结果如下所示:
product | total | ptype | pdate
p1 | 3.00 | VAR | (NULL)
p2 | 1.50 | sale | 02/03
p3 | 5.25 | base | 10/10
我通过执行以下操作来完成我需要的结果:
SELECT DISTINCT product
,(SELECT SUM(amount) FROM T as b GROUP BY b.product HAVING a.product = b.product ) as total
,(SELECT CASE WHEN COUNT(*) = 1 THEN a.ptype ELSE 'VAR' END from T as b GROUP BY b.product HAVING a.product = b.product) as ptype
,(SELECT CASE WHEN COUNT(*) = 1 THEN a.pdate ELSE NULL END from T as b GROUP BY b.product HAVING a.product = b.product) as pdate
FROM T as a
但我想知道是否有更有效的方法可以实现相同的结果。