我已经在堆栈中看到了其他问题但是我无法解决我的特定问题以下是示例表
status area
a1 b1
a2 b1
a1 b2
以下是我使用的查询
select count(*) as count, area, status from table group by area,status
给了我
1 b1 a1
1 b1 a2
1 b2 a1
我想要
0 b2 a2
也要显示
我知道我必须使用联接来执行此操作,所以我尝试了以下
select Distinct(t1.status) as ds,t2.* from table as t1
right join
(select count(*), area, status from table group by area,status) t2
on t2.status=t1.status;
但这只是给了我相同的结果而没有0
也试过这个,但显然有一个语法错误,我无法弄清楚
select t1.count,t2.ds,t1.area from
(select count(*) as count, area, status as ws from table group by area,status) t1
left join select distinct(status) as ds from table as t2
on t1.ws=t2.ds
答案 0 :(得分:2)
蒂姆在评论中指出:你需要以某种方式介绍缺失的记录,mysql将无法自行解决。
你可以做的是使用自联接在状态和区域值之间创建一个笛卡尔联接,然后再次在原始表上加入原始表并按分组进行计数:
select t1.status, t2.area, count(t3.status)
from (select distinct status from yourtable) t1
join (select distinct area from yourtable) t2
left join yourtable t3 on t3.status=t1.status and t3.area=t2.area
group by t1.status, t2.area
答案 1 :(得分:1)
尝试以下查询
SELECT COUNT(t.area) count, c_t.area, c_t.status
FROM
(SELECT * FROM (SELECT DISTINCT status
FROM table) t_status
CROSS JOIN (SELECT DISTINCT area
FROM table) t_area
) c_t
LEFT JOIN table t
ON t.area = c_t.area
AND t.status = c_t.status
GROUP BY c_t.area, c_t.status;
希望这可以帮助你。
答案 2 :(得分:0)
COUNT()
函数返回与指定条件匹配的行数。这意味着它的最小结果根据定义将为零 - 即COUNT()
无法返回“ nothing ”。