如果类别A数据不可用,则显示类别B在SQL中

时间:2017-05-06 09:42:07

标签: sql sql-server sql-server-2008

category    item    Price   status
       A    Mobile1 1300    2
       A    Mobile1 1300    3
       A    Mobile1 1300    2
       B    Mobile1 1200    2
       B    Mobile1 1200    2
       A    Mobile2 2000    2
       A    Mobile2 2000    2
       B    Mobile2 1800    2
       B    Mobile2 1800    2
       C    Mobile2 1300    2
       A    Mobile3 3000    3
       B    Mobile3 2500    2
       C    Mobile3 2000    2
       A    Mobile3 3000    3

这是我想要的数据显示结果如:

category    Item    Price   Status  quantity
       A    Mobile1 1300    2       2
       A    Mobile2 2000    2       2
       B    Mobile3 2500    2       1

我在下面尝试了查询:

select  category, Item, Price, Status, count(Category) quantity from table1
where status = 2 and category = case category when 'A' then 'A' else 'B' End
group by category, Item, Price,Status

我试图显示A类的所有数据,如果A类物品数据不可用,则显示B类物品

2 个答案:

答案 0 :(得分:0)

您可以union all使用not in,如下所示:

select category, Item, Price, status, count(Category) quantity
from table1
where status = 2
    and category = 'A'
group by category, Item, Price, status

union all

select category, Item, Price, status, count(Category) quantity
from table1
where status = 2
    and category = 'B'
    and item not in (
        select item
        from table1
        where status = 2
            and category = 'A'
        )
group by category, Item, Price, status

答案 1 :(得分:0)

您似乎想要优先考虑每个项目的类别。您可以使用dense_rank()作为优先级,然后使用聚合来获取所需类别的摘要:

select min(category) as category, item, avg(price) as price,
       max(status) as status, count(*)
from (select t1.*,
             dense_rank() over (partition by item
                                (case when category = 'A' then 1
                                      when category = 'B' then 2
                                      when category = 'C' then 3
                                      else 4
                                 end)
                                ) as seqnum
      from table1 t1
      where status = 2
     ) t1
where seqnum = 1
group by item;