SQL Server query - Selecting COUNT(*) with DISTINCT
在SQLServer2005中,我有一个表cm_production,它列出了所有已投入生产的代码。该表有票据编号、程序类型、程序名称和推送编号以及其他一些列。
目标:按程序类型和推送数统计所有不同的程序名
到目前为止,我拥有的是:
1 2 3 4 5 6 7 | DECLARE @push_number INT; SET @push_number = [HERE_ADD_NUMBER]; SELECT DISTINCT COUNT(*) AS COUNT, program_type AS [TYPE] FROM cm_production WHERE push_number=@push_number GROUP BY program_type |
这让我有了一段路,但它计算的是所有的程序名,而不是不同的程序名(我不希望在那个查询中这样做)。我想我就是不能在不选择程序名的情况下告诉它只计算不同的程序名。或者别的什么。
Count all the DISTINCT program names by program type and push number
号
1 2 3 4 5 | SELECT COUNT(DISTINCT program_name) AS COUNT, program_type AS [TYPE] FROM cm_production WHERE push_number=@push_number GROUP BY program_type |
号
我需要得到每个不同值的出现次数。列包含区域信息。我最后得到的简单SQL查询是:
1 2 3 4 | SELECT Region, COUNT(*) FROM item WHERE Region IS NOT NULL GROUP BY Region |
。
这会给我一个列表,比如:
1 2 3 4 | Region, COUNT Denmark, 4 Sweden, 1 USA, 10 |
您必须为不同的列创建一个临时表,然后从该表查询计数。
1 2 3 4 | SELECT COUNT(*) FROM (SELECT DISTINCT column1,column2 FROM tablename WHERE condition ) AS dt |
。
这是温度表
1 2 3 4 | SELECT COUNT(DISTINCT program_name) AS COUNT, program_type AS [TYPE] FROM cm_production WHERE push_number=@push_number GROUP BY program_type |
试试这个:
1 2 3 4 5 6 7 | SELECT COUNT(program_name) AS [COUNT],program_type AS [TYPE] FROM (SELECT DISTINCT program_name,program_type FROM cm_production WHERE push_number=@push_number ) dt GROUP BY program_type |
这是一个很好的例子,您希望获得存储在最后一个地址字段中的pincode计数。
1 2 3 4 5 6 7 8 9 | SELECT DISTINCT RIGHT (address, 6), COUNT(*) AS COUNT FROM datafile WHERE address IS NOT NULL GROUP BY RIGHT (address, 6) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | SELECT COUNT (DISTINCT NumTar),'PROPIAS' FROM ATM_TRANe WITH (nolock) WHERE Fecha>='2014-01-01' AND Fecha<='2015-05-31'AND NetDestino=0 AND SystemCodResp=0 GROUP BY NetDestino UNION SELECT SUM (contar),'FORANEAS' FROM ( SELECT COUNT(DISTINCT NumTar) AS contar FROM ATM_TRANe WITH (nolock) WHERE Fecha>='2014-01-01' AND Fecha<='2014-01-31' AND NetDestino!=0 AND SystemCodResp=0 GROUP BY NetDestino )dt |
。