2009-10-05 142 views
279

在SQL Server 2005中,我有一個表cm_production,其中列出了所有已投入生產的代碼。該表有一個ticket_number,program_type,和program_name和push_number以及其他一些列。SQL Server查詢 - 使用DISTINCT選擇COUNT(*)

目標:計數所有節目類型的DISTINCT程序名稱和推數

我至今是:

SELECT DISTINCT COUNT(*) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE [email protected]_number 
GROUP BY program_type 

這讓我中途有,但它的計算所有的程序名,而不是獨特的(我不希望它在該查詢中執行)。我想我無法圍繞如何讓它只計算不同的程序名而不選擇它們。或者其他的東西。

回答

478

計數所有節目類型的DISTINCT程序名稱 ,推動數字

SELECT COUNT(DISTINCT program_name) AS Count, 
    program_type AS [Type] 
FROM cm_production 
WHERE [email protected]_number 
GROUP BY program_type 

DISTINCT COUNT(*)將返回一個排的每個唯一計數。你想要的是COUNT(DISTINCT expression):評估組中每一行的表達式並返回唯一非空值的數量。

+4

謝謝郵遞區號的計數一個很好的例子。出於某種原因,我很難概念化SQL查詢。這工作完美。 – somacore 2009-10-05 19:29:35

+4

如何根據多個列獲取DISTINCT條目的計數?我試圖做'SELECT COUNT(DISTINCT col1,col2)',但是'COUNT'似乎把這個解釋爲錯誤的參數數目。 – 2014-05-04 20:50:47

+3

@Bepetersn:我建議你問一個單獨的問題 – 2014-05-04 21:24:08

13

試試這個:

SELECT 
    COUNT(program_name) AS [Count],program_type AS [Type] 
    FROM (SELECT DISTINCT program_name,program_type 
       FROM cm_production 
       WHERE [email protected]_number 
     ) dt 
    GROUP BY program_type 
11
SELECT COUNT(DISTINCT program_name) AS Count, program_type AS [Type] 
FROM cm_production 
WHERE [email protected]_number 
GROUP BY program_type 
64

我需要獲取每個不同值的出現次數。該列包含區域信息。 簡單的SQL查詢我結束了同是:

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

這將使我的列表一樣,說:

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

在postgresql中,你可以使用'count(*)'而不是'count(*)AS count'。 – ogirginc 2017-07-25 12:25:10

+0

嘿@ Netsi1964同樣的查詢使用,但我想區域,狀態,計數,它可以嗎?請幫助我 – 2017-10-31 09:07:05

18

你必須創建一個臨時表的不同列,然後查詢從該表計數

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

這裏dt的臨時表

+0

謝謝!我在很多數據庫中使用了很多SQL,這是我第一次將它定義爲一個臨時表,其中「as X」。 – Mmm 2015-10-16 02:50:19

+2

請注意,此處「dt」的正常術語是_derived_ table,而不是臨時表 – 8forty 2017-02-02 21:48:45

-5
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 
-1

這是你想要得到它存儲在最後地址字段

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