34,873
社区成员
发帖
与我相关
我的任务
分享CREATE TABLE [tb]([项目名称] NVARCHAR(10),[数量] INT)
INSERT [tb]
SELECT 'A1',2 UNION ALL
SELECT 'A2',3 UNION ALL
SELECT 'A1',-2 UNION ALL
SELECT 'A4',2
select * from tb where 项目名称 not in (select 项目名称 from tb group by 项目名称 having count(1) > 1)
select * from tb where 项目名称 in (select 项目名称 from tb group by 项目名称 having count(1) = 1)
drop table tb
/*
项目名称 数量
---------- -----------
A2 3
A4 2
(所影响的行数为 2 行)
项目名称 数量
---------- -----------
A2 3
A4 2
(所影响的行数为 2 行)
*/
select 项目名称, sum(数量) from tb group by 项目名称 having sum(数量)>0
--> 测试数据:[TB]
if object_id('[TB]') is not null drop table [TB]
create table [TB]([项目名称] varchar(2),[数量] int)
insert [TB]
select 'A1',2 union all
select 'A2',3 union all
select 'A1',-2 union all
select 'A4',2
select * from [TB]
where 项目名称 in (select 项目名称 from TB group by 项目名称 having sum(数量)>0)
/*
项目名称 数量
---- -----------
A2 3
A4 2
(所影响的行数为 2 行)
*/
drop table tb--------------------------------------------------------------------------
-- Author : htl258(Tony)
-- Date : 2010-04-26 11:21:46
-- Version:Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition on Windows NT 5.1 <X86> (Build 2600: Service Pack 3)
-- Blog : http://blog.csdn.net/htl258
--------------------------------------------------------------------------
--> 生成测试数据表:tb
IF NOT OBJECT_ID('[tb]') IS NULL
DROP TABLE [tb]
GO
CREATE TABLE [tb]([名称] NVARCHAR(10),[数量] INT)
INSERT [tb]
SELECT 'A1',2 UNION ALL
SELECT 'A2',3 UNION ALL
SELECT 'A1',-2 UNION ALL
SELECT 'A4',2
GO
--SELECT * FROM [tb]
-->SQL查询如下:
select 名称,SUM(数量) 数量 from tb group by 名称 having SUM(数量)>0
/*
名称 数量
---------- -----------
A2 3
A4 2
(2 行受影响)
*/
select 项目名称,sum(数量) from tb a
group by 项目名称
having sum(数量)>0SELECT NAME,SUM(QTY)
FROM TB
GORUP BY NAME