有没有办法将这两个查询合并为一个查询,以便我可以检索两个数据“系列”以进行图表处理,同时仍保持单个日期的关系?
SELECT
COUNT(j.id) AS power_count, jd.ber_rcvd
FROM
jobs j
INNER JOIN job_dates jd
ON jd.job_id = j.id
WHERE j.tech = 7 AND jd.ber_rcvd != '0000-00-00' GROUP BY jd.ber_rcvd;
SELECT
COUNT(j.id) AS transport_count, jd.ber_rcvd
FROM
jobs j
INNER JOIN job_dates jd
ON jd.job_id = j.id
WHERE j.tech = 1 AND jd.ber_rcvd != '0000-00-00' GROUP BY jd.ber_rcvd;
我正在寻找的是这样输出:
power_count | transport_count | ber_rcvd
11 | 3 | 2013-03-01
7 | 1 | 2013-03-02
答案 0 :(得分:4)
使用GROUP BY功能:
SELECT j.tech, COUNT( j.id ) AS ber_count
FROM job j
INNER JOIN job_dates jd ON jd.job_id = j.id
WHERE j.tech IN ( 7, 1 )
GROUP BY j.tech;
那应该给你两行,一个用于tech = 1,一个用于tech = 7。当您使用GROUP BY函数时,COUNT()适用于每个分组。
在回答更新的问题时,请尝试以下方法:
SELECT COUNT( IF(j.tech=7,1,NULL)) AS power_count, COUNT( IF( j.tech = 1, 1, NULL )) AS transport_count, jd.ber_rcvd
FROM
jobs j
INNER JOIN job_dates jd
ON jd.job_id = j.id
WHERE j.tech IN ( 1, 7 ) AND jd.ber_rcvd != '0000-00-00'
GROUP BY jd.ber_rcvd;
如果不是,请发布一些样本数据供我们使用。
答案 1 :(得分:1)
使用UNION ALL
,它看起来像
SELECT COUNT(j.id) AS ber_count, jd.ber_rcvd
FROM jobs j
INNER JOIN job_dates jd
ON jd.job_id = j.id
WHERE j.tech = 7
UNION ALL
SELECT COUNT(j.id) AS ber_count, jd.ber_rcvd
FROM jobs j
INNER JOIN job_dates jd
ON jd.job_id = j.id
WHERE j.tech = 1
但GROUP BY
是一种更好的方法,因为@Seth建议