2016-11-08 38 views
1

我想根據結果表中每列的特定條件從表中獲取行的數量。該表本身是一個臨時表。SQL查詢:每列值是基於臨時表上不同過濾器的aggergation

下面的查詢是我想要的東西來完成,但我不知道什麼是語法來得到它:

WITH table1 as(a huge inner joins between different tables) 

SELECT * 
FROM (
    (
     SELECT COUNT(*) 
     FROM table1 
     WHERE 
      column1 = 'value1' AND column2 > 0 
    ) AS Count1, 
    (
     SELECT COUNT(*) 
     FROM table1 
     WHERE 
      column1 = 'value1' AND column2 = 0 
    )AS Count2, 
    (
     SELECT COUNT(*) 
     FROM table1 
     WHERE 
      column1 = 'value2' AND column2 > 0 
    )AS Count3, 
    (
     SELECT COUNT(*) 
     FROM table1 
     WHERE 
      column1 = 'value2' AND column2 = 0 
    ) AS Count4 
) CountSummary 

這是不正確的語法,但我不知道如何完成這個概念在sql server中。

這是我得到目前,如果我做我的查詢等於第二部分的錯誤:select * from table1

Msg 252, Level 16, State 1, Line 1 
Recursive common table expression 'table1' does not contain a top-level UNION ALL operator. 

巨大的內部聯接查詢可以分開沒有任何錯誤運行。

------------------- UPDATE --------------------------

遞歸錯誤是由於將'table1'命名爲與內部連接查詢部分中的表相同,所以我擺脫了這一點,並且錯誤消失了。然後我嘗試了答案,他們都工作。

回答

1

也許是這樣的: -

select 
    sum(case when column1 = 'value1' and column2 > 0 then 1 else 0 end) as Count1, 
    sum(case when column1 = 'value1' and column2 = 0 then 1 else 0 end) as Count2, 
    sum(case when column1 = 'value2' and column2 > 0 then 1 else 0 end) as Count3, 
    sum(case when column1 = 'value2' and column2 = 0 then 1 else 0 end) as Count4 
from table1 
+0

當我嘗試這一點,我得到這個錯誤:遞歸公用表表達式「表1」不包含頂級UNION ALL運營商 – Andi

+0

你沒有提到table1是一個CTE ...你可以發佈你的其餘查詢,以便我們可以看到發生了什麼事情的完整故事? –

+0

對不起,我不知道這會影響解決方案。更新。 – Andi

1

這樣做:

WITH table1 as(a huge inner joins between different tables) 

SELECT * FROM 
    (
     SELECT COUNT(*) AS Count1 
     FROM table1 
     WHERE 
      column1 = 'value1' AND column2 > 0 
    ) AS Count1, 
    (
     SELECT COUNT(*) AS Count2 
     FROM table1 
     WHERE 
      column1 = 'value1' AND column2 = 0 
    ) AS Count2