SQL Server查询-使用DISTINCT选择COUNT(*)


431

在SQL Server 2005中,我有一个表cm_production,其中列出了已投入生产的所有代码。该表具有ticket_number,program_type,program_name和push_number以及其他一些列。

目标:按程序类型和推送编号计算所有DISTINCT程序名称

到目前为止,我有:

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

这让我感到很困惑,但是它计算的是所有程序名称,而不是不同的名称(我不希望它在该查询中执行)。我想我只是无法解决如何告诉它只选择不同程序名称而不选择它们的问题。或者其他的东西。

Answers:


729

按程序类型和推送编号计算所有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>):计算组中每一行的表达式,并返回唯一的非空值的数量。


110

我需要获取每个不同值的出现次数。该列包含地区信息。我最终得到的简单SQL查询是:

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

这会给我一个清单,例如:

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

嘿@ Netsi1964使用了相同的查询,但是我想要Region,State,Count,这可能吗?请帮助我

47

您必须为不同的列创建一个派生表,然后从该表中查询计数:

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

dt是一个派生表。


1
谢谢!我一生中在许多数据库中使用了很多SQL,这是我第一次必须使用“ as X”将其限定为临时表。
毫米

6
请注意,此处“ dt”的正常术语是派生表,而不是临时表
8forty

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

15

尝试这个:

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

-1

这是一个很好的示例,您想获取存储在地址字段末尾的Pincode的数量

SELECT DISTINCT
    RIGHT (address, 6),
    count(*) AS count
FROM
    datafile
WHERE
    address IS NOT NULL
GROUP BY
    RIGHT (address, 6)

-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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.