2013-06-20 103 views
2

我會發布我的查詢開始......SQL - UNION查詢中總

SELECT [copyright status], 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
GROUP BY [copyright status] 

UNION 

SELECT [lw status], 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
WHERE [lw status] = 'In Reserve' 
GROUP BY [lw status] 

UNION 

SELECT [lw status], 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
WHERE [lw status] = 'Published' 
GROUP BY [lw status]; 

(希望這是易於閱讀)

它的工作,我打算將它,不過,我想喜歡爲查詢添加更多功能。

在第一個SELECT查詢之後,我想添加一個額外的查詢,其中總計每個三個總和(關鍵信息,方法,研究)。我試圖加入的語法如下:

<Previous Query> 
UNION 
SELECT, 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
UNION 
<Next Query> 

然而,當我嘗試運行它,我得到它讀取「不列的聯合查詢的查詢所選的兩個表中的數字錯誤比賽。」

我不確定我是否對此過於抱負。

此外,是否有更有效的方式來格式化初始查詢?

如果有區別,圖層,版權狀態和狀態值將存儲在單獨的表中,並通過表格設計模式中的組合框繪製到資源表中。我正在使用Access 2003.

如果需要更多信息,請告訴我。

謝謝。

回答

2

列數必須等於爲union的所有部分。你可以只添加一個null第一欄爲您彙總行:

SELECT null, 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
+0

這樣一個簡單的解決方案,謝謝! – Squadinho

+1

@Squadinho:列名由「union」的第一部分設置,連續的部分不能更改它。你可以用'SELECT [版權狀態]作爲Total開始你的查詢,' – Andomar

1

您刪除lw status,並沒有選擇任何內容:

UNION 
SELECT 'SUM', 
sum(IIF(layer='key info',1,0)) AS [Key Info], 
sum(IIF(layer='approaches',1,0)) AS [Approaches], 
sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
UNION 
<Next Query> 
+0

這將使而不是'LW status' 3列,一個太少 – Andomar

+0

啊哈THX,我將修改 – mirkobrankovic

+0

這樣一個簡單的解決方案,謝謝! – Squadinho

1

各自選擇內UNION必須(在你的案件4)相同的字段數。 可能只是將「存根」字段添加到SELECT中,例如,空值?

UNION 
SELECT 
    NULL, -- <- STUB (for padding only) 
    sum(IIF(layer='key info',1,0)) AS [Key Info], 
    sum(IIF(layer='approaches',1,0)) AS [Approaches], 
    sum(IIF(layer='research',1,0)) AS [Research] 
FROM resources 
UNION 
+0

謝謝,沒有意識到你可以用這種方式使用NULL。 – Squadinho