[英]SQL Comparing values in two rows
我有以下各類商品的銷售數據:
category year salesVolume
1 2002 45
1 2003 47
2 2002 789
2 2003 908
3 2002 333
3 2003 123
41 2002 111
41 2003 90
現在我想比較2002年到2003年的銷量,按類別划分,並將結果寫為:
category salesIncreasing?
1 TRUE
2 TRUE
3 FALSE
41 FALSE
是否可以在SQL中執行此操作。 如果是這樣,請告訴我。 其實我使用的是Impala SQL。 謝謝。
SELECT
a.category,
CASE WHEN a.salesVolumes < b.salesVolumes THEN 'TRUE' ELSE 'FALSE' END AS salesIncreasing
FROM MyTable a
INNER JOIN MyTable b ON a.category = b.category
WHERE a.year = 2002
AND b.year = 2003
我們的想法是讓一張表作為結果,讓您比較銷售並將其投影到新數據中。 為此,您將表連接到自身,並在WHERE子句中使用兩個限制。
您可以使用條件聚合以及使用連接來執行此操作:
select fd.product,
sum(case when year = 2002 then SalesVolume end) as sales_2002,
sum(case when year = 2003 then SalesVolume end) as sales_2003,
(case when sum(case when year = 2002 then SalesVolume end) is null
then 'New2003'
when sum(case when year = 2003 then SalesVolume end) is null
then 'No2003'
when sum(case when year = 2002 then SalesVolume end) > sum(case when year = 2003 then SalesVolume end)
then 'Decreasing'
when sum(case when year = 2002 then SalesVolume end) = sum(case when year = 2003 then SalesVolume end)
then 'Equal'
else 'Increasing'
end) as Direction
from followingdata fd
where year in (2002, 2003)
group by fd.product;
這種方法優於join
的優點是它可以處理所有產品,甚至是那些兩年都沒有出現的產品。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.