選擇不同和聯合時出現問題

選擇不同和聯合時出現問題

我正在嘗試對兩個表中的年齡範圍計數進行求和。我能夠將兩個表中的總計顯示到一個視圖中,但無法弄清楚如何獲取 evac 中心重複項並將每個 evac 中心的所有總計顯示在一行上。

當我在每個表格中新增 Select Distinct 時,我會收到錯誤。

SELECT dbo.tblGenPopRegistration_DEV.EvacCenter AS [Evac Center], SUM(CASE WHEN dbo.tblGenPopRegistration_DEV.Age < 6 THEN 1 ELSE 0 END) AS [5 and Under], 
                         SUM(CASE WHEN dbo.tblGenPopRegistration_DEV.Age BETWEEN 6 AND 17 THEN 1 ELSE 0 END) AS [6 to 17], 
             SUM(CASE WHEN dbo.tblGenPopRegistration_DEV.Age > 17 THEN 1 ELSE 0 END) AS [18 and Over]
FROM  dbo.tblGenPopRegistration_DEV
WHERE        (dbo.tblGenPopRegistration_DEV.CheckedIn = 1)
Group by dbo.tblGenPopRegistration_DEV.EvacCenter
UNION ALL
SELECT dbo.tblGenPopAdditionalRegistrations_DEV.EvacCenter AS [Evac Center], SUM(CASE WHEN dbo.tblGenPopAdditionalRegistrations_DEV.Age < 6 THEN 1 ELSE 0 END) AS [5 and Under], 
                         SUM(CASE WHEN dbo.tblGenPopAdditionalRegistrations_DEV.Age BETWEEN 6 AND 17 THEN 1 ELSE 0 END) AS [6 to 17], 
             SUM(CASE WHEN dbo.tblGenPopAdditionalRegistrations_DEV.Age > 17 THEN 1 ELSE 0 END) AS [18 and Over]
FROM dbo.tblGenPopAdditionalRegistrations_DEV
Group by dbo.tblGenPopAdditionalRegistrations_DEV.EvacCenter

答案1

我希望我明白你想要什麼。

首先像這樣組合兩個 SELECT。請注意,我們使用 UNION 而不是 UNION ALL 來匹配您問題的第一部分取出疏散中心的副本

SELECT dbo.tblGenPopRegistration_DEV.EvacCenter AS [Evac Center], 
       dbo.tblGenPopRegistration_DEV.Age
FROM   dbo.tblGenPopRegistration_DEV
WHERE  (dbo.tblGenPopRegistration_DEV.CheckedIn = 1)
UNION
SELECT dbo.tblGenPopAdditionalRegistrations_DEV.EvacCenter AS [Evac Center], 
       dbo.tblGenPopAdditionalRegistrations_DEV.Age
FROM   dbo.tblGenPopAdditionalRegistrations_DEV

現在使用以下命令進行求和

SELECT EvacCenter AS [Evac Center], 
   SUM(CASE WHEN Age < 6 THEN 1 ELSE 0 END) AS [5 and Under], 
   SUM(CASE WHEN Age BETWEEN 6 AND 17 THEN 1 ELSE 0 END) AS [6 to 17], 
   SUM(CASE WHEN Age > 17 THEN 1 ELSE 0 END) AS [18 and Over]
FROM (
   SELECT dbo.tblGenPopRegistration_DEV.EvacCenter as EvacCenter, 
          dbo.tblGenPopRegistration_DEV.Age as Age
   FROM   dbo.tblGenPopRegistration_DEV
   WHERE  (dbo.tblGenPopRegistration_DEV.CheckedIn = 1)
   UNION
   SELECT dbo.tblGenPopAdditionalRegistrations_DEV.EvacCenter as EvacCenter, 
          dbo.tblGenPopAdditionalRegistrations_DEV.Age as Age
   FROM   dbo.tblGenPopAdditionalRegistrations_DEV
) GROUP BY EvacCenter

你問題的第二部分是將每個疏散中心的所有總計放在一行中。 我不知道我們是否已經有了這個結果。

如果沒有,請提供一個範例並提及您的 SQL 資料庫或 SQL 方言。我想您想要一個可以透過使用關鍵字獲得的結果

OVER PARTITION BY

相關內容