我的表结构是这样的
品牌     零售户ID  需求量
01       100        20
01       101        30
02       102        40
02       100        40
03       101        60我希望得到的结果是品牌     零售户数    总户数
01        2           3
02        2           3
03        1           3能否用1条sql文查询出来,我按照品牌分组只能得到前两列,最后的总户数表示不出来。

解决方案 »

  1.   

    create table tb(品牌 varchar(10),零售户ID varchar(10),需求量 int)
    insert into tb values('01', '100', 20)
    insert into tb values('01', '101', 30)
    insert into tb values('02', '102', 40)
    insert into tb values('02', '100', 40)
    insert into tb values('03', '101', 60)
    goselect 品牌 , count(零售户ID) 零售户数 , (select count(distinct 零售户ID) from tb) 总户数 from tb group by 品牌/*
    品牌         零售户数        总户数         
    ---------- ----------- ----------- 
    01         2           3
    02         2           3
    03         1           3(所影响的行数为 3 行)
    */select 品牌 , count(distinct 零售户ID) 零售户数 , (select count(distinct 零售户ID) from tb) 总户数 from tb group by 品牌/*
    品牌         零售户数        总户数         
    ---------- ----------- ----------- 
    01         2           3
    02         2           3
    03         1           3(所影响的行数为 3 行)
    */drop table tb
      

  2.   


    if object_id('tb') is not null
       drop table tb
    go
    create table tb
    (
     品牌 varchar(10),
     零售户ID int,
     需求量 int
    )
    go
    insert into tb
    select '01',100,20 union all
    select '01',101,30 union all
    select '02',102,40 union all
    select '02',100,40 union all
    select '03',101,60
    go
    select 品牌,零售户数=count(distinct 零售户ID),总户数=(select count(distinct 零售户ID) from tb) from tb group by 品牌
    go
    /*
    品牌         零售户数        总户数
    ---------- ----------- -----------
    01         2           3
    02         2           3
    03         1           3(3 行受影响)
    */
      

  3.   

    品牌 零售户ID 需求量
    01 100 20
    01 101 30
    02 102 40
    02 100 40
    03 101 60
    create table tbl(
    brandid varchar(4) not null,
    salesid varchar(4) not null,
    neednum int not null
    )insert into tbl values('01','100',20)
    insert into tbl values('01','101',30)
    insert into tbl values('02','102',40)
    insert into tbl values('02','102',40)
    insert into tbl values('03','101',60)我希望得到的结果是
    select 
    brandid as 品牌,
    count(salesid)as 零售户数,
    (select count(distinct salesid)from tbl)as 总户数
    from tbl
    group by
    brandid品牌 零售户数 总户数
    01 2 3
    02 2 3
    03 1 3
      

  4.   

    select 品牌,零售户数=count(*),
          总户数=(select count(distinct 零售户ID) from tb)
    from tb group by 品牌