1

我正在计算不同客户的数量并将其按另一列分组。如果在组中找不到客户,我希望结果返回零。使用以下代码,我的结果中不会出现零。有人可以帮忙吗?

SELECT download_date,resolution,COUNT(DISTINCT customer_id) FROM test.sample
GROUP BY download_date,resolution;

这给了我以下内容:

----------------------------------------
| 2011-06-09| HD       | 1             |
----------------------------------------
| 2011-06-09| SD       | 1             |
----------------------------------------
| 2012-06-10| SD       | 1             |
----------------------------------------

而我希望得到以下内容:

----------------------------------------
| 2011-06-09| HD       | 1             |
----------------------------------------
| 2011-06-09| SD       | 1             |
----------------------------------------
| 2012-06-10| HD       | 1             |
----------------------------------------
| 2012-06-10| SD       | 0             |
----------------------------------------

这是表结构:

CREATE TABLE test.sample (
`customer_id` VARCHAR(15) NULL DEFAULT NULL,
`download_date` DATE NULL DEFAULT NULL,
`resolution` VARCHAR(2) NULL DEFAULT NULL,
`total_units` INT(11) NULL DEFAULT NULL);

INSERT INTO test.sample(`customer_id`,`download_date`,`resolution`,`total_units`)
VALUES('1','2012-06-10','HD',40),('1','2012-06-10','HD',20),
('2','2011-06-09','SD',10),('2','2011-06-09','HD',20);
4

1 回答 1

1
select dr.download_date, r.resolution,COUNT(DISTINCT customer_id)
from
(select DISTINCT download_date from sample) dr
cross join
(select distinct resolution from sample) r
left join sample s on s.download_date = dr.download_date
and r.resolution = s.resolution
group by dr.download_date, r.resolution;

小提琴

于 2013-08-08T17:04:47.270 回答