开发者

Select multiple records from same table

开发者 https://www.devze.com 2023-03-14 06:34 出处:网络
I am trying to write a query that will select two different result from table. Let us suppose that following is table sale:

I am trying to write a query that will select two different result from table.

Let us suppose that following is table sale:

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

I want to select sum of sale products and returned products. So the following will be 开发者_Python百科the result:

Supp  Sale  Return
A       5      1
B       1      0

I am trying following query but not getting desired results

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

Will somebody tell me what will be query to get this result?


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

What was wrong with the original query:

First, you use COUNT() when you should use SUM().

Second you join two instances of table sale. This might have worked if you had used t.items >0 AND s.items < 0 But it would be more complex and you would need also t.supp = s.supp. Unneccecarily complexity (and it may not even work even then).

Third, the where t.items='1' and s.items='-1' conditions does not sum any rows with items different than 1 or -1. And you obsiously have some different, like the 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
0

精彩评论

暂无评论...
验证码 换一张
取 消