2013-04-16 94 views
0

我希望在兩個SQL查詢之間建立連接,在「WHERE」子句的兩個不同列中顯示相同的字段,如以下示例所示:concat sql查詢>根據where子句顯示相同的列2條不同的列根據where子句

查詢N°1:

SELECT COUNT([ID]) AS SOCIETE_1, 
     CAST([Créé le] AS date) AS DateCreated 
FROM [MFilesCloudReport].[dbo].[Document] 
WHERE [Société_ID] = 1 
GROUP BY CAST([Créé le] AS date) 
ORDER BY CAST([Créé le] AS date) 

- >結果N°1:

SOCIETE_1 DateCreated 
----------------------------------- 
142  | 2013-01-17 
148  | 2013-01-21 
88  | 2013-01-23 
188  | 2013-01-25 
187  | 2013-01-29 
124  | 2013-01-31 

查詢N°2:

SELECT COUNT([ID]) AS SOCIETE_2, 
    CAST([Créé le] AS date) AS DateCreated 
FROM [MFilesCloudReport].[dbo].[Document] 
WHERE [Société_ID] = 2 
GROUP BY CAST([Créé le] AS date) 
ORDER BY CAST([Créé le] AS date) 

- >結果N°2:

SOCIETE_2 DateCreated 
----------------------------------- 
18  | 2013-01-17 
73  | 2013-01-21 
75  | 2013-01-23 
1  | 2013-01-24 
48  | 2013-01-25 
80  | 2013-01-29 
43  | 2013-01-31 

預期的結果將是這一個:

SOCIETE_1  SOCIETE_2  TOTAL  DateCreated 
---------------------------------------------------------------------------- 
142   | 18  | 160  | 2013-01-17 
148   | 73  | 221  | 2013-01-21 
88   | 75  | 163  | 2013-01-23 
0   | 1  | 1  | 2013-01-24 
188   | 48  | 236  | 2013-01-25 
187   | 80  | 267  | 2013-01-29 
124   | 43  | 167  | 2013-01-31 

謝謝提前爲你的所有幫助和美好的一天。

+0

***什麼*** RDBMS是爲了這個嗎? SQL Server? MySQL的?甲骨文? Postgres的? Informix的? Interbase的?別的東西?????? –

回答

1
SELECT COUNT(case when [Société_ID] = 1 then [ID] end) AS SOCIETE_1, 
     COUNT(case when [Société_ID] = 2 then [ID] end) AS SOCIETE_2, 
     COUNT(*) AS TOTAL, 
     CAST([Créé le] AS date) AS DateCreated 
FROM [MFilesCloudReport].[dbo].[Document] 
GROUP BY CAST([Créé le] AS date) 
ORDER BY CAST([Créé le] AS date) 
+0

@JW是的,我同意,但取決於在「TOTAL」列中顯示的內容。 – paul

+0

它完美地工作。非常感謝你,我現在可以將這個方法應用於很多查詢:) 謝謝你的幫助和感謝社區:) – locas13