基于数据表计数多个列 - MySQL

时间:2013-09-08 02:07:57

标签: mysql sql join count

使用日期表,我正在尝试根据周计算不同的列。 我设法用一列来做,它工作正常。但是,当我计算多个列时,我得到错误或重复的结果。我认为这是因为加入。

这适用于预期的一列:

 SELECT
 DATE_FORMAT(thedate, '%u') as week
,COUNT(t.completed_date) as completed

FROM datetable
LEFT JOIN projects t ON t.completed_date = thedate
WHERE thedate BETWEEN YEAR(NOW()) AND NOW()
GROUP BY YEARWEEK(thedate,7)

通过将,COUNT(t.sales_date) as sales添加到选择中,我将获得已完成和销售的重复计数。

基于此示例(项目)

| id | completed_date | sales_date |
| 1  | NULL           | NULL       |
| 2  | NULL           | 2013-08-26 |
| 3  | NULL           | 2013-08-28 |
| 4  | 2013-09-06     | NULL       |

我正在寻找

| week | completed | sales |
| 34   | 0         | 0     |
| 35   | 0         | 2     |
| 36   | 1         | 0     |

我正在使用日期表,因为当没有日期时我需要所有日期为0。 我想我可以通过子查询来解决它,但是我还需要在此查询中计算12个其他日期字段(从示例中排除)。

有没有比使用大量子查询更好的解决方法?我的SQL有点生疏。

1 个答案:

答案 0 :(得分:1)

一种方法是使用按周分组每个值的子查询,然后将它们连接在一起。

SELECT d.week, completed, sales
FROM (SELECT YEARWEEK(thedate) week
      FROM datetable
      WHERE thedate BETWEEN YEAR(NOW()) AND NOW()
      GROUP BY week) d
LEFT JOIN (SELECT YEARWEEK(completed_date) week, COUNT(*) completed
           FROM projects
           WHERE completed_date BETWEEN YEAR(NOW()) AND NOW()
           GROUP BY week) c
ON c.week = d.week
LEFT JOIN (SELECT YEARWEEK(sales_date) week, COUNT(*) sales
           FROM projects
           WHERE sales_date BETWEEN YEAR(NOW()) AND NOW()
           GROUP BY week) s
ON s.week = d.week

这种方式更容易扩展到其他列:

SELECT DATE_FORMAT(thedate, '%u') AS week,
       IFNULL(SUM(completed_date = thedate), 0) AS completed,
       IFNULL(SUM(sales_date = thedate), 0) AS sales
FROM datetable
LEFT JOIN projects
ON thedate IN (completed_date, sales_date)
WHERE thedate BETWEEN YEAR(NOW()) AND NOW()
GROUP BY week