从三个表中选择计数并按一个字段分组

时间:2015-04-21 09:08:29

标签: sql sql-server

我有三个表,我希望按DateStart DateEnd分组,外键和计数行

表1:

start             end           FK

10/01/2014    12/01/2014    5
10/01/2014    13/01/2014    5


table 2
10/01/2014    12/01/2014    5
10/01/2014    13/01/2014    6

table 3 

10/01/2014    12/01/2014    5
10/01/2014    13/01/2014    7


Result

10/01/2014    12/01/2014    5     3 (rows)
10/01/2014    13/01/2014    5     1
10/01/2014    13/01/2014    6     1
10/01/2014    13/01/2014    7     1

编辑: 这是我的尝试(对于两个第一个表),它们没有按预期工作:

SELECT     query.IDchild as IDchild,
       Count(query.Number) as Number,
       query.DateStart as DateStart,
       query.DateEnd as DateEnd
(SELECT     RES.IDchild as IDchild,
       Count(RES.Number) as Number,
       RES.DateStart as DateStart,
       RES.DateEnd as DateEnd
FROM [dbo].[VA_R] as RES
WHERE (condition)
GROUP BY RES.IDchild  ,RES.DateStart,RES.DateEnd

Union all

SELECT     RES_o.IDchild as IDchild,
       Count(RES_o.Number) as Number,
       RES_o.DateStart as DateStart,
       RES_o.DateEnd as DateEnd
FROM [dbo].[VA_R_o] as RES_o
WHERE (condition)
GROUP BY RES_o.IDchild  ,RES_o.DateStart,RES_o.DateEnd, RES_o.PK_R) as query

GROUP BY RESqueryo.IDchild  ,query.DateStart,query.DateEnd

1 个答案:

答案 0 :(得分:1)

SELECT T.start, T.end, T.FK, COUNT(*)
FROM (
    SELECT start, end, FK
    FROM YourTable1

    UNION ALL

    SELECT start, end, FK
    FROM YourTable2

    UNION ALL

    SELECT start, end, FK
    FROM YourTable3
) AS T
GROUP BY T.start, T.end, T.FK

应该这样做。首先结合所有结果,然后按相关字段分组。正如评论中所述。