2

我有一个表字段为 (NAME FRUIT TIME)

|   NAME |  FRUIT |  TIME |
|--------|--------|-------|
|   AJAY |  MANGO | 10:10 |
| SACHIN |  APPLE | 12:00 |
|    RAJ |  MANGO | 10:00 |
|   AJAY |  MANGO | 12:00 |
|   AJAY |  MANGO | 11:00 |
|   AJAY |  APPLE | 12:00 |
|    RAJ | BANANA | 12:00 |
|   AJAY | BANANA | 12:00 |
| SACHIN | BANANA |  2:00 |
| SACHIN |  MANGO | 12:00 |
|    RAJ |  MANGO | 12:00 |
| SACHIN |  APPLE | 12:00 |
|   AJAY |  APPLE | 12:00 |
|   AJAY |  APPLE | 12:00 |

现在我想从上表中得到这样的输出:

|   NAME | MANGOCOUNT | APPLECOUNT | BANANACOUNT |
|--------|------------|------------|-------------|
|   AJAY |          3 |          3 |           1 |
|    RAJ |          2 |          0 |           1 |
| SACHIN |          1 |          2 |           1 |

我试过UNION这样:

SELECT NAME, COUNT(*) AS MANGOCOUNT FROM FRUIT_EAT 
 WHERE FRUIT='MANGO'  GROUP BY NAME 
UNION ALL 
SELECT NAME, COUNT(*) AS APPLECOUNT FROM FRUIT_EAT 
 WHERE FRUIT='APPLE' GROUP BY NAME 
UNION ALL 
SELECT NAME, COUNT(*) AS BANANACOUNT FROM FRUIT_EAT 
 WHERE FRUIT='BANANA' GROUP BY NAME;

我得到的结果是

NAME        MANGOCOUNT
AJAY           3
RAJ            2
SACHIN         1
AJAY           3
RAJ            0
SACHIN         2
AJAY           1
RAJ            1
SACHIN         1

我不明白我的错误。如果你能帮帮我吗?

4

1 回答 1

0

你不需要为此使用UNION。您可以使用如下SUM()函数和CASE语句来执行此操作:

SELECT Name
      ,SUM(CASE WHEN Fruit = 'Mango' THEN 1 ELSE 0 END) AS MangoCount
      ,SUM(CASE WHEN Fruit = 'Apple' THEN 1 ELSE 0 END) AS AppleCount
      ,SUM(CASE WHEN Fruit = 'Banana' THEN 1 ELSE 0 END) AS BananaCount
  FROM MyTable
 GROUP BY Name;

您还可以使用此动态查询:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN `Fruit` = ''',
      `Fruit`,
      ''' THEN 1 ELSE 0 END) AS `',
      `Fruit`, '`'
    )
  ) INTO @sql
FROM MyTable;

SET @sql = CONCAT('SELECT Name, ', @sql,'
                     FROM MyTable
                    GROUP BY Name
                  ');

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

输出:

|   NAME | MANGOCOUNT | APPLECOUNT | BANANACOUNT |
|--------|------------|------------|-------------|
|   AJAY |          3 |          3 |           1 |
|    RAJ |          2 |          0 |           1 |
| SACHIN |          1 |          2 |           1 |

看到这个 SQLFiddle

于 2013-09-14T04:25:12.927 回答