22,301
社区成员




create table tb(客户编号 varchar(10), 单据号 varchar(10), 货物编码 varchar(10), 发货标志 int)
insert tb select 'C01', 'D01', 'H01', 0
insert tb select 'C01', 'D02', 'H01', 1
insert tb select 'C01', 'D02', 'H02', 1
insert tb select 'C01', 'D02', 'H02', 1
insert tb select 'C01', 'D03', 'H01', 0
select 客户编号, 单据数= count(distinct 单据号), 货物种类 = count(distinct 货物编码),发货标志
from tb group by 客户编号,发货标志
/*
客户编号 单据数 货物种类 发货标志
---------- ----------- ----------- -----------
C01 2 1 0
C01 1 2 1
(2 行受影响)
*/
--> 数据库版本:
--> Microsoft SQL Server 2008 (RTM) - 10.0.1600.22
--> 测试数据:sellRecord
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'sellRecord')
AND type in (N'U'))
DROP TABLE sellRecord
GO
---->建表
create table sellRecord([客户编号] varchar(3),[单据号] varchar(3),[货物编码] varchar(3),[发货标志(0:未发货;1:已发货)] int)
insert sellRecord
select 'C01','D01','H01',0 union all
select 'C01','D02','H01',1 union all
select 'C01','D02','H02',1 union all
select 'C01','D02','H02',1 union all
select 'C01','D03','H01',0
GO
--> 查询结果
SELECT 客户编号, count(单据号),count(货物编码),[发货标志(0:未发货;1:已发货)]
FROM sellRecord
group by 客户编号,[发货标志(0:未发货;1:已发货)]
--> 删除表格
--DROP TABLE sellRecord