2017-04-17 118 views
0

我有包含Id,日期和狀態的表,即打開/關閉 我只想在sql中包含明智的開放,關閉和Id的總數的結果 例如在Jan Jan open計數15,靠近計數5和總計數20如何獲得特定行的計數

+0

提示:'GROUP BY'。 –

+1

可以給我舉個例子 – WeeZy

+1

你用什麼數據庫引擎? –

回答

0

使用匯總()和GROUP BY如下:

;WITH T AS 
(
    SELECT 
     Id,  
     DATENAME(MONTH,[Date]) AS [MonthName],   
     Status 
    FROM @tblTest 
) 
SELECT 
    [MonthName], 
    [Status], 
    StatusCount 
FROM 
(
    SELECT 
     MonthName, 
     CASE ISNULL(Status,'') WHEN '' THEN 'Total' ELSE Status END AS Status,   
     Count(Status) AS StatusCount       
    FROM T 
    GROUP BY ROLLUP([MonthName],[Status]) 
)X 
WHERE X.MonthName IS NOT NULL 
ORDER BY X.[MonthName],X.[Status] 

輸出:

enter image description here

注:如果一個月單列所需的數據然後申請PIVOT

+0

你的ans是絕對正確的,並且正在爲我工​​作,但是你能否只是詳細說明你的答案... – WeeZy

+0

我覺得你很熟悉團隊。另外還有RollUp和Cube功能,可以添加額外的行以添加組摘要/組頁腳。閱讀更多:https://oracle-base.com/articles/misc/rollup-cube-grouping-functions-and-grouping-sets –

+0

也看看這裏:http://stackoverflow.com/questions/7053471/understanding-立方體和彙總之間的差異 –

-1
select year(date), month(date), 
     sum(case when status = 'open' then 1 else 0 end) as open_count, 
     sum(case when status = 'closed' then 1 else 0 end) as closed_count, 
     count(*) as total_count 
from your_table 
group by year(date), month(date)