采购单号   采购数量   入库数量
CG0001       100        100
CG0002       200        100
CG0002       200        100
CG0003       300        150
CG0003       300        150
CG0004       400        400
一个采购单号可能对应多次入库
现在我要计算的采购数量合计
应该是比如: 100+200+300+400
SQL语句怎么写?

解决方案 »

  1.   

    select sum(采购数量) from (distinct * from tb) a
      

  2.   

    select sum(采购数量) from (select distinct * from tb) a
      

  3.   

    select sum(distinct 采购数量 ) from tb 
    group by 采购单号
      

  4.   

    select sum(采购数量) from (select distinct 采购单号,采购数量  from tb) a
      

  5.   

    select sum(distinct 采购数量 ) from [Table] 
      

  6.   

    select sum(采购数量) 采购数量 from 
    (select distinct 采购单号,采购数量  from tb) t
      

  7.   

    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([采购单号] varchar(6),[采购数量] int,[入库数量] int)
    insert [tb]
    select 'CG0001',100,100 union all
    select 'CG0002',200,100 union all
    select 'CG0002',200,100 union all
    select 'CG0003',300,150 union all
    select 'CG0003',300,150 union all
    select 'CG0004',400,400--------------------------------查询开始------------------------------
    --1
    select sum(distinct 采购数量 ) from tb 
    --2
    select sum([采购数量]) from (select distinct * from tb) a 
      

  8.   

    ----------------------------------------------------------------------------------
    -- Author : htl258(Tony)
    -- Date   : 2010-05-12 10:38:35
    -- 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 OBJECT_ID('[tb]') IS NOT NULL
    DROP TABLE [tb]
    GO
    CREATE TABLE [tb] ([采购单号] [nvarchar](10),[采购数量] [int],[入库数量] [int])
    INSERT INTO [tb]
    SELECT 'CG0001','100','100' UNION ALL
    SELECT 'CG0002','200','100' UNION ALL
    SELECT 'CG0002','200','100' UNION ALL
    SELECT 'CG0003','300','150' UNION ALL
    SELECT 'CG0003','300','150' UNION ALL
    SELECT 'CG0004','400','400'--SELECT * FROM [tb]-->SQL查询如下:
    SELECT SUM(采购数量) FROM (SELECT DISTINCT 采购单号,采购数量  FROM TB) A
    /*
    -----------
    1000(1 行受影响)
    */
      

  9.   


    select sum(distinct(purCount)) as 采购数量
    from tb
      

  10.   


    select sum([采购数量]) from (select distinct * from tb) a 
      

  11.   

    create table c
    (
    采购单号 varchar(22) not null,
    采购数量 int not null,
    入库数量 int not null
    )
    drop table cinsert into c select 'CG0001', 100, 100 union all
    select 'CG0002', 200, 100 union all
    select 'CG0002', 200, 100 union all
    select 'CG0003', 300, 150 union all
    select 'CG0003', 300, 150 union all
    select 'CG0004', 400, 400select sum(采购数量) as 采购数量 from (select distinct * from c)b