嵌套select语句中的where子句基于group by参数

时间:2016-04-25 12:17:06

标签: sqlite

我想形成一个类似下面的SQL查询,但无法弄清楚如何让它工作:

SELECT col_1 AS a,
       col_2 AS b,
       (SELECT sum(col_3)
        FROM table2
        WHERE col_1 = a
          AND col_2 = b) AS c
FROM table1
GROUP BY col_1, col_2;

1 个答案:

答案 0 :(得分:1)

列子别名在子查询中不可用。

您必须直接引用这些列:

SELECT col_1 AS a,
       col_2 AS b,
       (SELECT sum(col_3)
        FROM table2
        WHERE col_1 = table1.col_1
          AND col_2 = table1.col_2) AS c
FROM table1
GROUP BY col_1, col_2;