在同一个表上减去价格

时间:2017-01-23 05:58:15

标签: max self-join

我有一个包含以下列名称的表格。我想找到MAX的结果(NewyorkPrice-MANITOBAPrice,0)

IntertieZoneName    DeliveryHour    Price   
MANITOBA              1             16.2    
MANITOBA              2            19.0 
NEWYORK               1             14.4    
NEWYORK               2             20.0    

上的预期输出
Price   DeliveryHour
0       1
1.0     2

请帮我编写自助表上的Sql查询

1 个答案:

答案 0 :(得分:0)

SELECT CASE WHEN t.price_difference < 0 THEN 0 ELSE t.price_difference END AS Price,
       t.DeliveryHour
FROM
(
    SELECT DeliveryHour,
           MAX(CASE WHEN IntertieZoneName = 'NEWYORK'  THEN Price END) -
           MAX(CASE WHEN IntertieZoneName = 'MANITOBA' THEN Price END) AS price_difference
    FROM yourTable
    GROUP BY DeliveryHour
) t