如何在PHP中按年计算列中的项目数

时间:2013-04-08 13:11:18

标签: php mysql

这可能吗?我有下表

ID   CAR  MODEL  YEAR   FUELTYPE
1    Volvo S80   2007        GAS
2    Volvo S80D  2007        DIESEL
3    Volvo S80E  2009        LPN

我想要做的是按年计算不同的FUELTYPE,输出将是这样的,这是我想要使用的Google Chart的格式。

Year GAS DIESEL LPN
2007  1     1    0
2009  0     0    1

我怎样才能使用MySQL?我可以这样做吗?

SELECT YEAR, COUNT(FUELTYPE) AS GAS, COUNT (FUELTYPE) AS DIESEL, COUNT (FUELTYPE) AS LPN
FROM  CARDATA
GROUP BY FUELTYPE
ORDER BY YEAR

我知道这是不对的,因为我在每个FUELTYPE中获得相同的计数值 - 将它从mysql中拉出来然后使用php进行排序/计数会更好吗?

2 个答案:

答案 0 :(得分:2)

您可以使用带有CASE表达式的聚合函数将数据行数据转换为列:

select year,
  sum(case when fueltype = 'gas' then 1 else 0 end) gas,
  sum(case when fueltype = 'diesel' then 1 else 0 end) diesel,
  sum(case when fueltype = 'lpn' then 1 else 0 end) lpn
from yt
group by year

请参阅SQL Fiddle with Demo

如果您具有未知数量的FuelType值,则可以使用预准备语句生成动态SQL:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(CASE WHEN fueltype = ''',
      fueltype,
      ''' THEN 1 else 0 END) AS `',
      fueltype, '`'
    )
  ) INTO @sql
FROM yt;

SET @sql 
  = CONCAT('SELECT year, ', @sql, ' 
            from yt
            group by year');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQL Fiddle with Demo。这两个结果都是:

| YEAR | GAS | DIESEL | LPN |
-----------------------------
| 2007 |   1 |      1 |   0 |
| 2009 |   0 |      0 |   1 |

答案 1 :(得分:1)

如果只有三个FuelType,则MySQL中最简单的解决方案是使用GROUP BYSUM()

SELECT  Year,
        SUM(FUELTYPE = 'GAS') GAS,
        SUM(FUELTYPE = 'DIESEL') DIESEL,
        SUM(FUELTYPE = 'LPN') LPN
FROM    CARDATA
GROUP   BY YEAR

但如果您的FUELTYPE数量未知,则更优先考虑动态SQL。

SET @sql = NULL;

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('SUM(FUELTYPE = ''',
               FUELTYPE, ''') AS ',
               CONCAT('`', FUELTYPE, '`')
               )) INTO @sql
FROM CARDATA;

SET @sql = CONCAT('SELECT   Year, ', @sql, ' 
                   FROM CARDATA
                   GROUP BY YEAR');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

输出

╔══════╦═════╦════════╦═════╗
║ YEAR ║ GAS ║ DIESEL ║ LPN ║
╠══════╬═════╬════════╬═════╣
║ 2007 ║   1 ║      1 ║   0 ║
║ 2009 ║   0 ║      0 ║   1 ║
╚══════╩═════╩════════╩═════╝