从同一个表中选择多个记录

时间:2011-06-18 10:06:06

标签: sql-server sql-server-2005 tsql

我正在尝试编写一个查询,从表中选择两个不同的结果。

让我们假设以下是桌面促销:

 Supp                           items
 A                                 1
 A                                 1
 A                                 3
 A                                -1 //negative represent return item
 B                                 1

我想选择销售产品和退货产品的总和。所以结果如下:

Supp  Sale  Return
A       5      1
B       1      0

我正在尝试关注查询但未获得所需结果

select 
t.Supp, count(t.items)'Quantity', count(s.items)'ReturnedQuantity'  
from sale t, sale s  
where t.items='1' and s.items='-1'
group by
   t.supp,s.supp   
order by
  sum(cast(t.items as int)) desc

有人会告诉我什么是查询来获得这个结果吗?

2 个答案:

答案 0 :(得分:3)

SELECT 
      Supp
    , SUM( CASE WHEN items > 0 
                THEN items
                ELSE 0
           END
         )
      AS SoldQuantity
    , - SUM( CASE WHEN items < 0 
                  THEN items
                  ELSE 0
             END
           )
      AS ReturnedQuantity
FROM sale   
GROUP BY Supp   
ORDER BY SoldQuantity DESC         --- or ORDER BY Supp
                                   --- whatever is needed

原始查询出了什么问题:

首先,当您使用COUNT()时,请使用SUM()

其次,您加入表sale的两个实例。如果您使用t.items >0 AND s.items < 0,这可能会有效但但它会更复杂,您还需要t.supp = s.supp。不一致的复杂性(即便如此也可能不起作用)。

第三,where t.items='1' and s.items='-1'条件不会对包含1-1的项目的任何行进行求和。而且你有些不同,比如3

答案 1 :(得分:3)

SELECT t.Supp AS 'Supp', SUM(t.items) AS 'Sale', SUM(t.return_items) AS 'Return'  FROM           (
    SELECT Supp AS Supp,
    CASE WHEN items < 0 THEN 0 ELSE items END AS items,
    CASE WHEN items > 0 THEN 0 ELSE -items END AS return_items
    FROM tb_Test
) AS t
GROUP BY t.Supp
ORDER BY 'Sale' desc