给出表结构create table tb
(
itemId nvarchar(40),
itemNum int,
area    nvarchar(30)
)insert into tb
select '1',1,'北京' union all select '2',7,'北京' union all select '3',5,'北京' union all
select '4',2,'上海'
union all
select '5',9,'上海'
union all
select '6',7,'大连'
union all
select '7',30,'大连'
drop table tbarea 分组 查出 小于 5的ID数量select area,count(1) as 数量 from tb
where itemNum <5
group by area问题:现在要做   小于2   ,小于5, 小于30 这样3个
用left join 连接的话这个方法比较笨,效率却不错。试问!!!!有没有更好的办法?????????????

解决方案 »

  1.   

    create table tb
    (
    itemId nvarchar(40),
    itemNum int,
    area    nvarchar(30)
    )insert into tb
    select '1',1,'北京' union all select '2',7,'北京' union all select '3',5,'北京' union all
    select '4',2,'上海'
    union all
    select '5',9,'上海'
    union all
    select '6',7,'大连'
    union all
    select '7',30,'大连'select t.area ,
           (select count(1) from tb where area = t.area and itemNum < 2) [<2],
           (select count(1) from tb where area = t.area and itemNum < 5) [<5],
           (select count(1) from tb where area = t.area and itemNum < 30) [<30]
    from tb t
    group by area
    drop table tb/*
    area                           <2          <5          <30         
    ------------------------------ ----------- ----------- ----------- 
    北京                             1           1           3
    大连                             0           0           1
    上海                             0           1           2(所影响的行数为 3 行)*/
      

  2.   

    create table tb
    (
    itemId nvarchar(40),
    itemNum int,
    area    nvarchar(30)
    )insert into tb
    select '1',1,'北京' union all select '2',7,'北京' union all select '3',5,'北京' union all
    select '4',2,'上海'
    union all
    select '5',9,'上海'
    union all
    select '6',7,'大连'
    union all
    select '7',30,'大连'--select * from tb
    select
      area,
      max(case when itemNum<2 then 1 else 0 end) as [<2],
      max(case when itemNum<5 then 1 else 0 end) as [<5],
      max(case when itemNum<30 then 1 else 0 end) as [<30]
    from
      tb
    group by
      areadrop table tb
    /*area                           <2          <5          <30
    ------------------------------ ----------- ----------- -----------
    北京                             1           1           1
    大连                             0           0           1
    上海                             0           1           1(3 行受影响)
    */