如何计算SQL中临时列的总和?

时间:2014-02-19 19:11:04

标签: mysql sql mysql-workbench

我有这段代码:

SELECT
    ID,
    name,
    result,
    CASE
        WHEN result = 1 THEN 100
        WHEN result = 2 THEN 80
        ELSE NULL
    END AS TemporaryColumn
FROM MyTable

这就是表格:

| ID | Name | result | TemporaryColumn |
----------------------------------------
|  1 |  A   |   1    |      100        |
----------------------------------------
|  2 |  B   |   1    |      100        |
----------------------------------------
|  3 |  C   |   2    |      80         |
----------------------------------------
|  1 |  A   |   2    |      80         |
----------------------------------------
|  2 |  B   |   1    |      100        |
----------------------------------------
|  3 |  C   |   2    |      80         |
----------------------------------------

我想找到每个ID的sum(),表格应如下所示:

| ID | Name | result | TemporaryColumn |
----------------------------------------
|  1 |  A   |   1    |      180        |
----------------------------------------
|  2 |  B   |   1    |      200        |
----------------------------------------
|  3 |  C   |   2    |      160        |
----------------------------------------

我该如何查询?

1 个答案:

答案 0 :(得分:1)

这样的东西
SELECT
    ID,
    name,
    result,
    SUM(
        CASE
            WHEN result = 1 THEN 100
            WHEN result = 2 THEN 80
            ELSE NULL
        END
    ) AS TemporaryColumn
FROM MyTable
GROUP BY ID,
    name

不要因为我所知道的result列无法保证,它不是唯一的,应该从选择列表中排除。

如果是这种情况,则必须使用

SELECT
    ID,
    name,
    SUM(
        CASE
            WHEN result = 1 THEN 100
            WHEN result = 2 THEN 80
            ELSE NULL
        END
    ) AS TemporaryColumn
FROM MyTable
GROUP BY ID,
    name