我有一张这样的表:
id model status
1 Star 1
2 Star 0
3 Bana 0
4 Ship 1
5 Star 1
6 Ship 1
7 Ship 0
8 Bana 1
9 Bana 1
10 Ship 0
11 Ship 0
我想要这个:
Model On Off
Ship 2 3
Star 2 1
Bana 2 1
我试过这个但是太长了,当我在桌上有8000条记录时......
SELECT a.model,
(SELECT count(b.status) lib
FROM SpaceShips b
WHERE a.model=b.model
AND b.status='1'
GROUP BY b.model) ON,
(SELECT count(c.status) blo
FROM SpaceShips c
WHERE a.model=c.model
AND c.status='0'
GROUP BY c.model) OFF
FROM SpaceShips a
WHERE (a.status='0'
OR a.status='1')
GROUP BY model
ORDER BY model
答案 0 :(得分:2)
你可以这样做:
SELECT
model,
SUM(status='0') AS Off,
SUM(status='1') AS On
FROM
SpaceShips
GROUP BY
model
- 我在样本所需的输出中看不到任何顺序,所以我跳过了它
答案 1 :(得分:0)
试试这个:
SELECT
model,
sum(if(status=1,1,0)) as on,
sum(if(status=0,1,0)) as off
FROM
SpaceShips
GROUP BY
model
ORDER BY
model