我需要从具有不同条件的表中检索日期,并将每个不同的数据与总和放在不同的列中。经过大量测试后,我有了这个查询,但它太慢而且太大,而且它没有检索所有单位:
SELECT cal.dt, cal.h, a.measure, b.measure, c.measure, d.measure, e.measure, f.measure, g.measure, h.measure, ud.unit_name
FROM calendar cal
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 0 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) a
ON a.date_bid = dt AND a.hour = h
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 1 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hora, id_unit, id_agent) b
ON b.date_bid = dt AND b.hour = h AND a.id_unit = b.id_unit AND a.id_agent = b.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 2 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) c
ON c.date_bid = dt AND c.hour = h AND a.id_unit = c.id_unit AND a.id_agent = c.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 3 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) d
ON d.date_bid = dt AND d.hour = h AND a.id_unit = d.id_unit AND a.id_agent = d.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 4 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) e
ON e.date_bid = dt AND e.hour = h AND a.id_unit = e.id_unit AND a.id_agent = e.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agente FROM MEASURES
WHERE sesion = 5 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) f
ON f.date_bid = dt AND f.hour = h AND a.id_unit = f.id_unit AND a.id_agent = f.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agente FROM MEASURES
WHERE sesion = 6 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) g
ON g.date_bid = dt AND g.hour = h AND a.id_unit = g.id_unit AND a.id_agent = g.id_agent
LEFT JOIN (SELECT date_bid, hour, ROUND(SUM(measure),3) as measure, id_unit, id_agent FROM MEASURES
WHERE sesion = 7 AND date_bid BETWEEN '02/27/2013' AND '02/28/2013' GROUP BY date_bid, hour, id_unit, id_agent) h
ON h.date_bid = dt AND h.hour = h AND a.id_unit = h.id_unit AND a.id_agent = h.id_agent
INNER JOIN FACILITIES ud ON a.id_unit = ud.id_unit
WHERE cal.dt BETWEEN '02/27/2013' AND '02/28/2013' AND a.id_agent = 42
--GROUP BY a.date_bid, a.hour, ud.unit_name
ORDER BY cal.dt, ud.unit_name, cal.h
我之前尝试过直接在没有子选择的表之间使用 JOINS,但没有工作,因为每个结果的数量可能不同sesion
。
现在的问题是,除了此查询需要大量时间之外,它仅检索出现在第一个子选择 ( sesion = 1
) 上的单元的数据,并且当一个单元中没有数据时,不显示其余的数据。
我认为应该有更好的方法来面对这个查询。