concat sql query>根据where子句在2个不同的列中显示相同的列

时间:2013-04-16 13:19:30

标签: sql union concat

我希望在两个sql查询之间建立连接,在“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

提前感谢您的帮助和美好的一天。

1 个答案:

答案 0 :(得分: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)