用下一个相同id的值替换零 - MySQL

时间:2012-05-12 08:13:16

标签: php mysql views

我使用另一个表并生成MySQL视图,使用我编写的视图:

SELECT staffid,
   CASE Frequency
     WHEN 'Less' THEN COUNT(Frequency)
     ELSE '0'
  END AS LessCount,
  CASE Frequency
     WHEN 'Full' THEN COUNT(Frequency)
     ELSE '0'
  END AS FullCount,
  CASE Frequency
     WHEN 'More' THEN COUNT(Frequency)
     ELSE '0'
  END AS MoreCount
FROM effort_frequency
GROUP BY staffid, Frequency

我使用上面的代码来获得下表:

+-------+-----------+-----------+-----------+
| staff | lessCount | FullCount | MoreCount |
+-------+-----------+-----------+-----------+
|   10  |    2      |    0      |    0      |
|   10  |    0      |    1      |    0      |
|   10  |    0      |    0      |    3      |
|   11  |    1      |    0      |    0      |
|   11  |    0      |    3      |    0      |
+-------+-----------+-----------+-----------+

我需要转换它,看起来应该是这样的:

+-------+-----------+-----------+-----------+
| staff | lessCount | FullCount | MoreCount |
+-------+-----------+-----------+-----------+
|   10  |    2      |    1      |    3      |
|   11  |    1      |    3      |    0      |
+-------+-----------+-----------+-----------+

我们如何在MySQL中做到这一点?

1 个答案:

答案 0 :(得分:2)

SELECT   staffid               AS staff,
         SUM(Frequency='Less') AS lessCount,
         SUM(Frequency='Full') AS FullCount,
         SUM(Frequency='More') AS MoreCount
FROM     effort_frequency
GROUP BY staffid