SQL查询 - 中间的两个分组结果在查询中

时间:2013-09-20 15:51:16

标签: mysql sql

我有一个相当长而复杂的查询,最终产生这样的结果:

item_id  |  shop_id   |   sold
   5           3            0
   5           3            1
   5           3            1
   8           4            0
   8           6            1
   8           9            0

我需要以某种方式做SELECT item_id, COUNT(DISTINCT (shop_id)) FROM tableAbove GROUP BY item_id来获得:

    item_id   | number of shops that sell/have sold item
       5                1
       8                3

但是,我还需要每个项目成功销售它的商店数量,所以像这样:

    item_id    |  number of shops that have sold item
       5                    1
       8                    1

有谁知道如何在查询中将它们放在一起来提供

    item_id    |  shops that sell item  |number of shops that have sold item
       5                     1                         1
       8                     3                         1

1 个答案:

答案 0 :(得分:3)

SELECT  item_id,
        COUNT(DISTINCT shop_id),
        COUNT(DISTINCT CASE WHEN sold = 1 THEN shop_id END)
FROM    my_query
GROUP BY
        item_id