2016-11-29 83 views
1

我有一個查詢,我想分組顯示每個值的數量在一個字段中的數量,並希望聯合第二個查詢應該顯示總計和所有項目的計數。這是我的查詢的摘要。MS ACCESS SQL如何聯盟與組通過顯示總計

SELECT a.[Field to Count], Count(a.[Field to Count]) as Count 
FROM MyTable as a 
Where a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
Group By a.[Field to Count] 
UNION 
SELECT "Grand Total", Count(*) 
FROM MyTable as a 
Where a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
Group By ? 

什麼是想是這樣的:
場伯爵=========計數
值1 ================值1的計數
Value2 ================值的計數2
Value3 ================計數值3
「Grand Total」 =========所有字段的計數值

我知道,沒有Group By在第二個查詢中它不會顯示任何東西,所以我知道我需要使用它。基本上像「分組*」

有什麼建議嗎?

回答

1

我不確定在第二個查詢中是否需要GROUP BY,或者如果這樣做更有意義。相反,只需選擇總表計數:

SELECT t.label, t.count 
FROM 
(
    SELECT a.[Field to Count] AS label, 
      COUNT(*) AS count, 
      0 AS pos 
    FROM MyTable as a 
    WHERE a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
    GROUP BY a.[Field to Count] 
    UNION 
    SELECT "Grand Total" AS label, 
      COUNT(*) AS count, 
      1 AS pos 
    FROM MyTable as a 
    WHERE a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
) t 
ORDER BY t.pos, t.label 

注意,我加了一個計算列posUNION每個子查詢可以訂購總計最後。請注意,在外部查詢中,我實際上並未選擇pos,因爲我們不希望它在結果集中,我們只希望它用於排序。

+0

嘿什麼是行: '0作爲POS' 和 '1 AS POS機' 呢? –

+0

@RobertMazurowski我在'UNION'的每個子查詢中添加一個計算列,以便您的總計最後顯示。這可能已經在原始查詢中發生,但不能保證。 –

+0

感謝編輯,這是一個非常好的答案 –

1

減少添的一點是外選擇不需要:

SELECT a.[Field to Count] AS label, 
     COUNT(*) AS [count], 
     0 AS pos 
FROM MyTable as a 
WHERE a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
GROUP BY a.[Field to Count] 
UNION 
SELECT "Grand Total" AS label, 
     COUNT(*) AS [count], 
     1 AS pos 
FROM MyTable as a 
WHERE a.[Some Field] = "Value1" AND a.[Some other Field] <> "Some value" 
ORDER BY 2, 1 
+0

古斯塔夫你爲什麼把數字放在[]括號內? –

+0

設計師做到了。我想這是因爲它是一個保留字,儘管我相信查詢將不會運行。 – Gustav

+0

Gustav ORDER BY部分似乎不起作用,它說a.pos不是select語句的一部分。 –