SQL Server查询 – 用DISTINCTselectCOUNT(*)

在SQL Server 2005中,我有一个表cm_production,列出了所有已投入生产的代码。 该表有一个ticket_number,program_type和程序名和push_number连同其他一些列。

目标:按程序types和推送号码统计所有的DISTINCT程序名称

我到目前为止是:

SELECT DISTINCT COUNT(*) AS Count, program_type AS [Type] FROM cm_production WHERE push_number=@push_number GROUP BY program_type 

这让我在那里,但它计数所有的程序名称,而不是独特的(我不希望它在该查询中)。 我想我只是不能包装我的头如何告诉它只计算不同的程序名称,而不select它们。 或者其他的东西。

按程序types和推送号码计算所有的DISTINCT程序名称

 SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] FROM cm_production WHERE push_number=@push_number GROUP BY program_type 

DISTINCT COUNT(*)将为每个唯一计数返回一行。 你想要的是COUNT(DISTINCT expression式 ) :计算组中每一行的expression式,并返回唯一的非空值的数量。

我需要得到每个不同值的出现次数。 该列包含区域信息。 我结束了简单的SQL查询是:

 SELECT Region, count(*) FROM item WHERE Region is not null GROUP BY Region 

这会给我一个像这样的名单,说:

 Region, count Denmark, 4 Sweden, 1 USA, 10 

您必须为不同的列创build临时表,然后从该表中查询计数

 SELECT COUNT(*) FROM (SELECT DISTINCT column1,column2 FROM tablename WHERE condition ) as dt 

这里dt是一个临时表

尝试这个:

 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 
 SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] FROM cm_production WHERE push_number=@push_number GROUP BY program_type 

这是一个很好的例子,你想要得到存储在最后一个地址字段中的Pincode的数量

 SELECT DISTINCT RIGHT (address, 6), count(*) AS count FROM datafile WHERE address IS NOT NULL GROUP BY RIGHT (address, 6) 
 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