我调整了 sgeddes 的出色答案以实际获得计数并避免重复条目,并添加了一个支持脚本,以便您对其进行测试。这确实假设 SQL Server。
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'MYTABLE') BEGIN
drop table MYTABLE;
END;
go
create table MYTABLE
(
state nvarchar(2)
,county nvarchar(100)
,city nvarchar(100)
,zip nvarchar(10)
)
go
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94541');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94541');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94544');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94545');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94546');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','LIVERMORE','94550');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','LIVERMORE','94551');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','CASTRO VALLEY','94552');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','HAYWARD','94552');
insert into MYTABLE(state,county,city,zip) values('CA','ALAMEDA','FREMONT','94555');
select distinct
t.state
,t.county
,t.zip
,t2.sumcount
,STUFF((
SELECT distinct '/' + city AS [text()]
FROM mytable t3
WHERE t.zip = t3.zip
FOR XML PATH('')
), 1, 1, '') AS ColList
from
mytable t
inner join
(
select zip, sum(count) as sumcount
from
(
select zip,count(*) as count
from mytable
group by zip
) x
group by zip
) t2
on t.zip=t2.zip
输出如下所示:
state county zip sumcount ColList
CA ALAMEDA 94541 2 HAYWARD
CA ALAMEDA 94544 1 HAYWARD
CA ALAMEDA 94545 1 HAYWARD
CA ALAMEDA 94546 9 CASTRO VALLEY/HAYWARD
CA ALAMEDA 94550 1 LIVERMORE
CA ALAMEDA 94551 1 LIVERMORE
CA ALAMEDA 94552 2 CASTRO VALLEY/HAYWARD
CA ALAMEDA 94555 1 FREMONT