遇到分组求和的有关问题
遇到分组求和的问题
建表脚本
表的数据如下:
shelfid goodsid statusid
1 1 13
1 2 13
1 3 13
2 4 13
2 5 13
2 6 13
1 1 14
1 2 14
1 3 14
2 4 14
2 5 14
我想得到
shelfid goodsidcount
1 3
2 2
求高手指点下,非常感谢
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
建表脚本
if exists (select * from sysobjects where id = OBJECT_ID('[testtb]') and OBJECTPROPERTY(id, 'IsUserTable') = 1)
DROP TABLE [testtb]
CREATE TABLE [testtb] (
[shelfid] [varchar] (50) NOT NULL,
[goodsid] [varchar] (50) NOT NULL,
[statusid] [int] NOT NULL)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'1',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'2',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'3',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'2',N'4',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'2',N'5',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'2',N'6',13)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'1',14)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'2',14)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'1',N'3',14)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'2',N'4',14)
INSERT [testtb] ([shelfid],[goodsid],[statusid]) VALUES ( N'2',N'5',14)
表的数据如下:
shelfid goodsid statusid
1 1 13
1 2 13
1 3 13
2 4 13
2 5 13
2 6 13
1 1 14
1 2 14
1 3 14
2 4 14
2 5 14
我想得到
shelfid goodsidcount
1 3
2 2
SQL
select
脚本
行业数据
对象
------解决方案--------------------
select shelfid,count(distinct goodsid) 'goodsidcount'
from testtb
group by shelfid
/*
shelfid goodsidcount
-------------------------------------------------- ------------
1 3
2 3
(2 row(s) affected)
*/
------解决方案--------------------
select shelfid,COUNT(goodsidcount )goodsidcount
FROM (
SELECT shelfid,COUNT(goodsid) goodsidcount
FROM testtb
GROUP BY shelfid,goodsid
HAVING COUNT(goodsid)>1)a
GROUP BY shelfid
------解决方案--------------------