我目前正在使用此查询..
SELECT sub_id, pm_id, count(*) AS expect FROM `sub_performancemeasures`
WHERE `progress`='0' GROUP BY pm_id
这是查询生成的表..
sub_id | pm_id | expect
1 | 162 | 4
1 | 163 | 6
5 | 164 | 2
1 | 168 | 5
我还有其他几乎相同的查询...
SELECT sub_id, pm_id, count(*) AS stretch FROM `sub_performancemeasures`
WHERE `progress`='100' GROUP BY pm_id
SELECT sub_id, pm_id, count(*) AS poor FROM `sub_performancemeasures`
WHERE `progress`='-100' GROUP BY pm_id
SELECT sub_id, pm_id, count(*) AS excel FROM `sub_performancemeasures`
WHERE `progress`='200' GROUP BY pm_id
我想要做的是将所有这些合并到一个查询中,结果看起来像这样..
sub_id | pm_id | poor | expect | stretch | excel
1 | 162 | 4 | 0 | 2 | 5
1 | 163 | 6 | 9 | 4 | 1
5 | 164 | 2 | 1 | 7 | 9
1 | 168 | 5 | 3 | 5 | 8
答案 0 :(得分:4)
您没有加入,而是可以使用conditional sum
作为
select
sub_id,
pm_id,
sum( case when `progress`='0' then 1 else 0 end ) as expect,
sum( case when `progress`='100' then 1 else 0 end ) as stretch,
sum( case when `progress`='-100' then 1 else 0 end ) as poor,
sum( case when `progress`='200' then 1 else 0 end ) as excel
from `sub_performancemeasures`
group by pm_id
另请注意,在标准sql中,每个非聚合列都应该在group by子句中,但在mysql中它允许不具有它,但是你应该删除select中不需要的列。
答案 1 :(得分:0)
尝试此操作(派生表上的LEFT JOIN)。这适用于期望和伸展,然后您可以轻松扩展为穷人和excel(或将来甚至更多列):
SELECT sub.sub_id, sub.pm_id, CASE WHEN
temp_expect.expect IS NOT NULL THEN temp_expect.expect ELSE '0' END AS expect,
CASE WHEN temp_stretch.stretch IS NOT NULL
THEN temp_stretch.stretch ELSE '0' END AS stretch
FROM sub_performancemeasures sub
LEFT JOIN
(
SELECT pm_id, count(*) AS expect FROM `sub_performancemeasures`
WHERE `progress`='0' GROUP BY pm_id
)
AS temp_expect ON sub.pm_id = temp_expect.pm_id
LEFT JOIN
(
SELECT pm_id, count(*) AS stretch FROM `sub_performancemeasures`
WHERE `progress`='100' GROUP BY pm_id
)
AS temp_stretch ON sub.pm_id = temp_stretch.pm_id
答案 2 :(得分:0)
您可以尝试以下查询: -
{{1}}