0

我有一个包含三列的表:

LOCATION |   ITEM    |  QUANTITY
--------------------------------
001       RED CAR      1
002       RED CAR      3
003       BLUE CAR     5
002       BLUE CAR     2
001       RED CAR      2
002       RED CAR      5



我试图运行一个查询,它会告诉我每个位置有多少个独特的项目。我在同一个位置有多行的原因是每个位置可能有多个人同时输入记录。

目标是获取项目总数和每个位置输入的总数。

ITEM     | LOCATION 001 | LOCATION 002 | LOCATION 003 |  TOTAL
--------------------------------------------------------------
RED CAR    3              8              0               11
BLUE CAR   0              2              5               7



我无法想出一个 SELECT 查询来获取每个位置的总数和每个项目的总数。我试图用一个查询来完成这个,而不是运行两个单独的查询请求。任何帮助将不胜感激。

我有测试链接来尝试一些不同的查询。
http://www.sqlfiddle.com/#!2/c33cee/1/0

4

2 回答 2

1

如果事先知道所有位置,您可以这样做

SELECT item,
       SUM(CASE WHEN location = 1 THEN quantity ELSE 0 END) location_001,
       SUM(CASE WHEN location = 2 THEN quantity ELSE 0 END) location_002,
       SUM(CASE WHEN location = 3 THEN quantity ELSE 0 END) location_003,
       SUM(quantity) total
  FROM car_uploads
 GROUP BY item

输出:

| 项目 | LOCATION_001 | LOCATION_002 | LOCATION_003 | 总计 |
------------|-------------|--------------|-------- ------|-------|
| 蓝车 | 0 | 2 | 5 | 7 |
| 红车 | 3 | 8 | 0 | 11 |

这是SQLFiddle演示

于 2013-08-24T06:00:23.727 回答
1

试试这个查询:

SELECT ITEM
  ,SUM(CASE WHEN LOCATION = 001 THEN QUANTITY ELSE 0 END) AS Location_001
  ,SUM(CASE WHEN LOCATION = 002 THEN QUANTITY ELSE 0 END) AS Location_002
  ,SUM(CASE WHEN LOCATION = 003 THEN QUANTITY ELSE 0 END) AS Location_003
  ,SUM(Quantity) AS Total
FROM Table1
GROUP BY ITEM;

如果你不知道 Locations,你可以试试这个动态查询:

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

SET @sql = CONCAT('SELECT ITEM, ', @sql,'
                     ,SUM(Quantity) AS Total 
                     FROM Table1
                    GROUP BY ITEM
                  ');

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

结果:

|     ITEM | 1 | 2 | 3 | TOTAL |
|----------|---|---|---|-------|
| BLUE CAR | 0 | 2 | 5 |     7 |
|  RED CAR | 3 | 8 | 0 |    11 |

看到这个 SQLFiddle

于 2013-08-24T06:06:16.473 回答