项目名称,数量 
A1        2    
A2        3
A1        -2
A4        2
用什么语句,只找到 
A2   3
A4   2

解决方案 »

  1.   

    SELECT NAME,SUM(QTY)
    FROM TB
    GORUP BY NAME
      

  2.   


    select 项目名称,sum(数量) from tb a
    group by 项目名称
    having sum(数量)>0
      

  3.   

    --------------------------------------------------------------------------
    --  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
    --------------------------------------------------------------------------
    --> 生成测试数据表:tbIF 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 行受影响)
    */
      

  4.   


    --> 测试数据:[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
      

  5.   


    --> 测试数据:[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
      

  6.   


    select 项目名称, sum(数量) from tb group by 项目名称 having sum(数量)>0
      

  7.   


    select * from tb where 项目名称 not in (select 项目名称 from tb group by 项目名称 having count(1) > 1)
      

  8.   

    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',2select * 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 行)
    */