在一列中获取项目及其值的计数

时间:2011-09-05 12:04:52

标签: sql sql-server-2008

考虑以下表格:

Table Items:

ItemID    ItemName
------------------
 1          N1
 2          N2 
 3          N4
 4          N5

在MyTbl表中我有一个ItemID,可能是这样的:

ItemId
----
1
1
3
4
4
4

我想编写一个返回此结果的查询:

ItemId        count
-------------------
   1            2
   2            0
   3            1
   4            3

如果没有游标我该如何做到?

2 个答案:

答案 0 :(得分:6)

您可以在公共Items上选择LEFT JOINMyTbl ItemID中的每件商品,计算匹配数量;

select 
   Items.itemId,
   count(MyTbl.itemId) as count
from Items
   left join MyTbl on (MyTbl.ItemID = Items.ItemID)
group by Items.itemId
order by Items.itemId

答案 1 :(得分:2)

试试这个:

declare @Items as table(ItemID int,ItemName varchar(20))
declare @MyTbl as table(ItemId int)

insert into  @Items values(1, 'N1')
insert into  @Items values(2, 'N2') 
insert into  @Items values(3, 'N4')
insert into  @Items values(4, 'N5')

insert into @MyTbl values(1)
insert into @MyTbl values(1)
insert into @MyTbl values(3)
insert into @MyTbl values(4)
insert into @MyTbl values(4)
insert into @MyTbl values(4)

select I.ItemID, COUNT(M.ItemId) as [COUNT] from  @Items I left outer join @MyTbl M on I.ItemID = M.ItemId
    group by I.ItemID