SQL a comparar valores em duas linhas

tenho os seguintes dados de vendas para várias categorias de itens:

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

agora eu quero comparar o volume de vendas no ano 2002 ao ano 2003, Categoria wise, e escrever os resultados como:

category        salesIncreasing?
1                 TRUE
2                 TRUE
3                 FALSE
41                FALSE
É possível fazê-lo em SQL. Se sim, por favor, avise-me. Na verdade, estou a usar o Impala SQL. Obrigado.

 3
sql
Author: user3282777, 2014-08-03

2 answers

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
A ideia é ter uma tabela única que permita comparar e projectar as vendas em novos dados. A fim de fazer isso, você se junta à tabela com ele mesmo, e você usa duas restrições na cláusula onde.
 7
Author: David Khuu, 2014-08-03 09:56:23

Você pode fazer isso com Agregação condicional, bem como usando uma junção:

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;

A vantagem desta abordagem sobre a join é que ela lida com todos os produtos, mesmo aqueles que não aparecem em ambos os anos.

 2
Author: Gordon Linoff, 2014-08-03 12:39:49