下面是我的SQL表。
Id FileName Code1 Code2
1 002-03_001.tif Y179 Y179
2 002-03_002.tif Y178 Y178
3 002-03_003.tif Y177 Y177
4 002-03_004.tif Y178 Y179
5 002-03_005.tif Y177 Y179
6 002-03_006.tif Y179 Y178
7 002-03_007.tif Y178 Y178
8 002-03_008.tif Y178 Y177
9 002-03_009.tif Y177 Y179
10 002-03_010.tif Y178 Y177
从上表我想要计算Code1和code2,如
Code1 Count1 Code2 Count2
Y177 3 Y177 3
Y178 2 Y178 3
Y179 5 Y179 4
答案 0 :(得分:2)
示例数据
create table table1
(
Id int,FileName VARCHAR(100),Code1 VARCHAR(10),Code2 VARCHAR(10)
)
insert into table1 values( 1, '002-03_001.tif', 'Y179', 'Y179'),
(2 ,'002-03_002.tif', 'Y178', 'Y178')
,(3 ,'002-03_003.tif', 'Y177', 'Y177')
,(4 ,'002-03_004.tif', 'Y178', 'Y179')
,(5 ,'002-03_005.tif', 'Y177', 'Y179')
,(6 ,'002-03_006.tif', 'Y179', 'Y178')
,(7 ,'002-03_007.tif', 'Y178', 'Y178')
,(8 ,'002-03_008.tif', 'Y178', 'Y177')
,(9 ,'002-03_009.tif', 'Y177', 'Y179')
,(10 ,'002-03_010.tif', 'Y178', 'Y177')
<强>查询强>
SELECT * FROM
(
SELECT Code1,COUNT(*) Count1
FROM table1
GROUP BY Code1
) Code1
INNER JOIN
(
SELECT Code2,COUNT(*) Count2
FROM table1
GROUP BY Code2
) Code2
ON Code1.Code1 = Code2.Code2