Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在单个SQL查询中使用多重计数和分组条件_Sql_Count_Group By_Union All - Fatal编程技术网

如何在单个SQL查询中使用多重计数和分组条件

如何在单个SQL查询中使用多重计数和分组条件,sql,count,group-by,union-all,Sql,Count,Group By,Union All,下面是我的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

下面是我的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
从上面的表格中,我要计算代码1和代码2

  Code1 Count1 Code2 Count2
  Y177   3      Y177    3
  Y178   2      Y178    3
  Y179   5      Y179    4

你想这样做吗

样本数据

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