2

我有一张这样的桌子:

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
4

2 回答 2

2

你可以这样做:

SELECT
  model,
  SUM(status='0') AS Off,
  SUM(status='1') AS On
FROM
  SpaceShips
GROUP BY
  model

-我在您的示例所需输出中看不到任何顺序,所以我跳过了它

于 2013-10-28T12:18:27.260 回答
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
于 2013-10-28T12:19:30.987 回答