Sql联盟将多个表连在一起

时间:2017-09-14 00:31:47

标签: sql sql-server-2008

我正在尝试使用联合从4个不同的表中获取总数,但我不确定如何使其工作..

我的单表计数代码工作正常,

SELECT (Select count(*) 
        FROM (SELECT RN, DP, DT, Min(ED) AS MinDate 
              FROM ECount1 
              GROUP BY RN, DP, DT) as x 
        WHERE DT = 'STR'  
          AND MONTH(MinDate) >= '07' 
          AND Month(MinDate) <= '09') as StrAFT

我以为我可以添加一个联盟,但这不起作用? 像这样的东西?

SELECT (Select count(*) FROM 
(SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount1 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
UNION
SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount2 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
UNION
SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount3 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
UNION
SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount4 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
) as StrAFT

2 个答案:

答案 0 :(得分:0)

我相信你遇到的问题是UNION,它会删除重复的行
您可以使用UNION ALL来保留这些重复的行

Select count(*) FROM 
(
    SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount1 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
    UNION ALL
    SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount2 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
    UNION ALL
    SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount3 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
    UNION ALL
    SELECT RN, DP, DT, Min(ED) AS MinDate FROM ECount4 GROUP BY RN, DP, DT) as x WHERE DT = 'STR' AND MONTH(MinDate) >= '07' and Month(MinDate) <= '09'
) as StrAFT

简化案例

-- This will return 1 row with 1
SELECT 1 UNION SELECT 1

-- This will return 2 rows with 1
SELECT 1 UNION ALL SELECT 1

根据e_i_pi的建议,您可以移除第一个SELECT (),它在您的查询中不执行任何操作

答案 1 :(得分:0)

根据Prissioner建议使用UNION ALL

WITH cte as (
    SELECT * FROM ECount1 
    UNION ALL
    SELECT * FROM ECount2
    UNION ALL
    SELECT * FROM ECount3 
    UNION ALL
    SELECT * FROM ECount4
), calculate as (
    SELECT RN, DP, DT, Min(ED) AS MinDate 
    FROM cte 
    WHERE DT = 'STR'  
      AND MONTH(ED) >= '07' 
      AND MONTH(ED) <= '09
    GROUP BY RN, DP, DT
    HAVING MIN(ED) IS NOT NULL
)
SELECT COUNT(*) 
FROM calculate

对于每个月的计数,请使用GROUP BY

 SELECT MONTH(ED), COUNT(*)
 FROM calculate
 GROUP BY MONTH(ED)

或使用条件计数:

 SELECT COUNT(*), 
        COUNT (CASE WHEN MONTH(ED) = '07' THEN 1 END) as count_07,
        COUNT (CASE WHEN MONTH(ED) = '08' THEN 1 END) as count_08,
        COUNT (CASE WHEN MONTH(ED) = '09' THEN 1 END) as count_09
 FROM calculate
 GROUP BY MONTH(ED)