sqlite多个查询条件

时间:2019-03-07 16:07:51

标签: sqlite

我已经搜索了,但找不到正确的答案,我正在绕圈转。 我有

CREATE TABLE History (yr Int, output Int, cat Text);
yr          output      cat
----------  ----------  ----------
2015        10          a
2016        20          a
2017        30          a
2018        50          a
2019        70          a
2015        100         b
2016        200         b
2017        300         b
2018        500         b
2019        700         b
2015        1000        c
2016        2000        c
2017        3000        c
2018        5000        c
2019        7000        c
2015        10000       d
2016        20000       d
2017        30000       d
2018        50000       d
2019        70000       d

我已经创建了两个视图

CREATE VIEW Core AS select  * from History where cat = "c" or cat = "d";

CREATE VIEW Plus AS select  * from History where cat = "a" or cat = "b";

我的查询是

select distinct yr, sum(output), (select sum(output) from core  group by yr) as _core, (select sum(output) from plus  group by yr) as _plus from history group by yr;

yr          sum(output)  _core       _plus
----------  -----------  ----------  ----------
2015        11110        11000       110
2016        22220        11000       110
2017        33330        11000       110
2018        55550        11000       110
2019        77770        11000       110

每个单独的查询都可以,但是_core和_plus列放在一起时是错误的。我该如何处理呢?

1 个答案:

答案 0 :(得分:0)

您可以使用带有条件聚合的单个查询来生成没有视图的预期输出:

SELECT
    yr,
    SUM(output) AS sum_output,
    SUM(CASE WHEN cat IN ('c', 'd') THEN output ELSE 0 END) AS _core,
    SUM(CASE WHEN cat IN ('a', 'b') THEN output ELSE 0 END) AS _plus
FROM History
GROUP BY
    yr;

如果您真的想使当前的方法可行,一种方法是仅按年份加入这两种视图。但这将使每个视图可能不会每年都存在的可能性成为可能。