SQL查询总和和行总数

时间:2013-08-24 05:55:34

标签: mysql sql database select join

我有一个包含三列的表:

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

2 个答案:

答案 0 :(得分: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

输出:

|     ITEM | LOCATION_001 | LOCATION_002 | LOCATION_003 | TOTAL |
-----------|--------------|--------------|--------------|-------|
| BLUE CAR |            0 |            2 |            5 |     7 |
|  RED CAR |            3 |            8 |            0 |    11 |

这是 SQLFiddle 演示

答案 1 :(得分: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;

如果您不知道位置,可以尝试以下动态查询:

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 |

请参阅this SQLFiddle