不同表中的多个查询

时间:2011-10-03 05:41:37

标签: sql

(同时发布here。)

所以我有两个表,一个是invalid表,另一个是valid表。

valid表:

id
status
date

invalid表:

id
status
date

我必须使用此输出生成报告:

date       on-time  late  total  valid  invalid1  invalid2  total  rate
---------  -------  ----  -----  -----  --------  --------  -----  ----
9/10/2011  4        10    14     3      3         3         6   
  • date:2个表上的常用字段,分组字段,当天有多少条记录
  • on-time:有效表中所有ID的计数
  • late:无效表
  • 上所有记录(id)的计数
  • total:总计及时和晚
  • valid:具有“有效”状态的有效表上的ID计数
  • invalid1:无效表上具有“invalid1”状态的ID的计数
  • invalid2:无效表上的ID为“invalid2”状态
  • total:有效,无效1,无效2
  • rate:总计平均值

它基本上是具有不同表的多个查询。我怎样才能实现它?

3 个答案:

答案 0 :(得分:2)

这样的东西?

SELECT
    *,
    (result.total + result._total) / 2 AS rate
FROM (
    SELECT
        date,
        SUM(CASE WHEN data.valid = 1 THEN 1 ELSE 0 END) AS ontime,
        SUM(CASE WHEN data.valid = 0 THEN 1 ELSE 0 END) AS late,
        COUNT(*) AS total,
        SUM(CASE WHEN data.valid = 1 AND data.status = 'valid' THEN 1 ELSE 0 END) AS valid,
        SUM(CASE WHEN data.valid = 0 AND data.status = 'invalid1' THEN 1 ELSE 0 END) AS invalid1,
        SUM(CASE WHEN data.valid = 0 AND data.status = 'invalid2' THEN 1 ELSE 0 END) AS invalid2,
        SUM(CASE WHEN data.status IN ('valid', 'invalid', 'invalid2') THEN 1 ELSE 0 END) AS _total

    FROM (
        SELECT
            date,
            status,
            valid = 1
        FROM
            Valid
        UNION ALL
        SELECT
            date,
            status,
            valid = 0
        FROM
            InValid ) AS data
    GROUP BY
        date) AS result

答案 1 :(得分:1)

SELECT date, ontime, late, ontime+late total, valid, invalid1, invalid2, valid+invalid1+invalid2 total
FROM
(SELECT date,
       COUNT(*) late,
       COUNT(IIF(status = 'invalid1', 1, NULL)) invalid1,
       COUNT(IIF(status = 'invalid2', 1, NULL)) invalid2,
FROM invalid
GROUP BY date
) JOIN (
SELECT date,
       COUNT(*) ontime,
       COUNT(IIF(status = 'valud', 1, NULL)) valid,
FROM valid
GROUP BY date
) USING (date)

答案 2 :(得分:0)

首先,您似乎在2个表中保存完全相同的信息 - 我建议将这些表合并在一起并添加一个名为valid的其他布尔列来保存与记录有效性相关的信息

对现有数据库结构的查询可能如下所示:

SELECT unioned.* FROM (
   ( SELECT v.date AS date, v.status AS status, v.id AS id, COUNT(id) AS valid, 0 AS invalid1, 0 AS invalid2 FROM valid v GROUP BY v.date)
    UNION
   ( SELECT i1.date AS date, i1.status AS status, i1.id AS id, 0 AS valid, COUNT(i1.id) AS invalid1, 0 AS invalid2 FROM invalid1 i1 GROUP BY i1.date)
   UNION
   ( SELECT i2.date AS date, i2.status AS status, i2.id AS id, 0 AS valid, 0 AS invalid1, COUNT(i.id) AS invalid2 FROM invalid1 i1 GROUP BY i1.date)

) AS unioned GROUP BY unioned.date