使用union和2个表时检索单个记录

时间:2017-05-04 15:51:22

标签: mysql union

我使用以下sql从2个表中获取每个月的总工作数。导入表是尚未完成的实时作业,import_archive表包含已完成的作业。

我需要从两个表中计算每周的所有工作并显示它们。

我正在使用以下可用的SQL,但显示了两个表中作业的重复周记录。我需要将它们加在一起,以便在同一周显示1条记录而不是2条记录。

(SELECT
    WEEKOFYEAR(Job_Start_Date) AS weekno, 
    COUNT(1) AS Jobs,
    SUBDATE(Job_Start_Date, INTERVAL WEEKDAY(Job_Start_Date) DAY) AS Week_Start_Date
FROM import where Job_Work_Type='PPD'
GROUP BY WEEKOFYEAR(Job_Start_Date))
union

(SELECT
    WEEKOFYEAR(Job_Start_Date) AS weekno, 
    COUNT(1) AS Jobs,
    SUBDATE(Job_Start_Date, INTERVAL WEEKDAY(Job_Start_Date) DAY) AS Week_Start_Date
FROM import_archive where Job_Work_Type='PPD'
GROUP BY WEEKOFYEAR(Job_Start_Date))

为什么我需要更改为每周只显示一条记录,即使正在使用2个表?

1 个答案:

答案 0 :(得分:0)

首先需要UNION ALL两个表start_dates然后解析你的计数和日期。 UNION所有这些都是因为我们希望保留重复的日期,因为它们可能用于不同的工作。如果您需要更多数据/列,请确保在进行分析/操作之前将两个集合合并。

简单地说:生成包含两个表中所有数据的主数据集,然后进行计数/数据操作。

SELECT WEEKOFYEAR(Job_Start_Date) AS weekno
     , COUNT(1) AS Jobs
     , SUBDATE(Job_Start_Date, INTERVAL WEEKDAY(Job_Start_Date) DAY) AS Week_Start_Date
FROM (SELECT Job_Start_date
      FROM import where Job_Work_Type='PPD'
      UNION ALL
      SELECT Job_Start_date
      FROM import_archive where Job_Work_Type='PPD')
GROUP BY WEEKOFYEAR(Job_Start_Date

或者您必须在生成两个不同的数据集后再次聚合。

SELECT weekno, sum(jobs) as jobs, week_start_Date
FROM (
(SELECT WEEKOFYEAR(Job_Start_Date) AS weekno
      , COUNT(1) AS Jobs
      , SUBDATE(Job_Start_Date, INTERVAL WEEKDAY(Job_Start_Date) DAY) AS Week_Start_Date
FROM import where Job_Work_Type='PPD'
GROUP BY WEEKOFYEAR(Job_Start_Date)
)
union

(SELECT WEEKOFYEAR(Job_Start_Date) AS weekno
      , COUNT(1) AS Jobs
      , SUBDATE(Job_Start_Date, INTERVAL WEEKDAY(Job_Start_Date) DAY) AS Week_Start_Date
 FROM import_archive where Job_Work_Type='PPD'
 GROUP BY WEEKOFYEAR(Job_Start_Date)
)
)
GROUP BY weekNo, weekStart_date