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