2

使用日期表,我试图根据周数计算不同的列。我设法用一列来做到这一点,而且效果很好。但是当我计算多列时,我得到错误或重复的结果。我想是因为加入。

这适用于预期的一列:

 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 有点生疏了。

4

1 回答 1

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
于 2013-09-08T02:58:00.120 回答