主表id   数量              操作              类型  
55627 310.0   1   W-1
55627 300.0   1   W-2
55627 300.0   2   W-1
怎么根据类型查询操作2的数量
条件:当操作2的类型和操作1的类型不一样则查询出来的数量为0
     当操作2的类型和操作1的类型一样则,查询出来的数量为min(数量)

解决方案 »

  1.   


    SELECT COUNT(*) FROM MainTable AS it
    WHERE it.id IN (SELECT id FROM MainTable AS a
                       WHERE a.操作 = 2 AND it.类型 IN (SELECT 类型 FROM MainTable AS b
                                                           WHERE b.操作 = 1))
    不知道这样行不行!
      

  2.   

    create table tb(id int,数量 decimal(10,1),操作 int,类型 varchar(10))
    insert into tb select 55627,310.0,1,'W-1'
    insert into tb select 55627,300.0,1,'W-2'
    insert into tb select 55627,300.0,2,'W-1'
    select id,类型,min(数量) from(
    select * from tb a where exists(select 1 from tb where 操作<>a.操作 and 类型=a.类型)
    )t group by id,类型
    go
    drop table tb
    /*id          类型         
    ----------- ---------- ---------------------------------------
    55627       W-1        300.0(1 行受影响)
    */
      

  3.   

    create table aa
    (
     id varchar(5) ,
     num int,
     op varchar(10),
     type varchar(10))
    insert into aa(id,num,op,type)
    select '55627',310,'1','W-1' union all
    select '55627',300,'1','W-2' union all
    select '55627',300,'2','W-1'select id,type,min(num) from (
    select * from aa a where  exists(select 1 from aa where a.op<>aa.op and a.type=aa.type))t
    group by id,type
    drop table aa