2011-10-03 113 views
3

(也貼here多個查詢

所以我有兩個表,一個是invalid表,另一個是valid表。

valid表:

id 
status 
date 

invalid表:

id 
status 
date 

我不得不產生這種輸出報告:在2公共字段:

date  on-time late total valid invalid1 invalid2 total rate 
--------- ------- ---- ----- ----- -------- -------- ----- ---- 
9/10/2011 4  10 14  3  3   3   6 
  • date Ť ABLES,場小組通過,有多少條記錄在那一天有
  • on-time:在有效的表中的所有ID的數量
  • late:對無效的表
  • total所有記錄(ID)數:對時間總計和
  • valid:與「有效」狀態的有效表ID的數量
  • invalid1:與「invalid1」狀態
  • invalid2無效的表ID的計數:計數ID與 「invalid2」 狀態
  • total無效表:總有效invalid1的,invalid2
  • rate:平均總量

這是一個與不同的表基本上多個查詢。我怎樣才能實現它?

+0

儘量正確地格式化您的文章,請。我試過了,但我不知道「total」和「total rate」是不是2列。 – Icarus

+0

他們是兩個不同的列 –

+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 
+0

謝謝ou!這正是我需要的! –

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) 
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 
+0

它給了我ff錯誤:列'unioned.valid'在選擇列表中無效,因爲它不是包含在聚合函數或GROUP BY子句中。列'unioned.invalid1'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。列'聯合。invalid2'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 –