0

有没有办法将这两个查询组合成一个查询,以便我可以检索两个数据“系列”以用于图表目的,同时仍保持单个日期的关系?

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 | 运输计数 | ber_rcvd 
11 | 3 | 2013-03-01
7 | 1 | 2013-03-02
4

2 回答 2

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;

那应该给你两行,一排技术= 1,一排技术= 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;

如果不是这样,请发布一些示例数据供我们使用。

于 2013-04-12T16:12:15.227 回答
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 建议的那样,这是一种更好的方法

于 2013-04-12T16:12:02.017 回答