-1

这可能吗?我有下表

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

我想做的是按年份计算不同的燃料类型,输出会是这样的,这是我想使用的谷歌图表的格式。

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 进行排序/计数会更好吗?

4

2 回答 2

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 |
于 2013-04-08T13:13:19.850 回答
1

如果只有三个FuelType,最简单的解决方案MySQL是使用GROUP BY, 和SUM()

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 ║
╚══════╩═════╩════════╩═════╝
于 2013-04-08T13:13:50.490 回答