用1列查询不同条件

时间:2018-10-16 03:54:09

标签: sql postgresql

我的桌子像:

+-------+--------+----------+------------+-------+
| cd_hs | cd_cnt | name_cnt |   dates    | value |
+-------+--------+----------+------------+-------+
|     1 |      1 | aaa      | 2018-06-01 |    50 |
|     1 |      2 | bbb      | 2018-07-01 |   150 |
|     1 |      3 | ccc      | 2018-08-01 |    20 |
|     1 |      1 | aaa      | 2018-06-02 |    40 |
|     1 |      2 | bbb      | 2018-07-02 |    70 |
|     1 |      3 | ccc      | 2018-08-02 |    80 |
+-------+--------+----------+------------+-------+

实际上我有更多数据,但我只是显示示例,而我想做的就是

我想按cd_hs列中的name_cntyeardates分组并执行sum(value),但我有2个条件。首先是显示条件为cd_cnt with 1 and 2的值,第二个条件为cd_cnt without 1 and 2的值,这意味着我除了1和2以外还有很多值,并且在一列中将别名为other

预期结果:

+-------+------+----------+-------------+
| cd_hs | year | name_cnt | total_value |
+-------+------+----------+-------------+
|     1 | 2018 | aaa      |          90 |
|     1 | 2018 | bbb      |         220 |
|     1 | 2018 | other    |         100 |
+-------+------+----------+-------------+

我该怎么做?我是查询的新手,不知道该怎么办。

1 个答案:

答案 0 :(得分:1)

考虑到您的规格似乎与您的要求不完全一致,您的问题有点令人困惑。

如果您提供的示例结果实际上是 ,那么简单的SUMGROUP BY应该可以这里的把戏:

SELECT cd_hs, EXTRACT(YEAR from dates) as year, name_cnt, SUM(value_)
FROM foo
GROUP BY cd_hs, EXTRACT(YEAR from dates), name_cnt

结果:

| cd_hs | year | name_cnt | sum |
|-------|------|----------|-----|
|     1 | 2018 |      aaa |  90 |
|     1 | 2018 |      bbb | 220 |
|     1 | 2018 |      ccc | 100 |

SQLFiddle


由于您提到要在两个不同的条件下获得两个不同的总数,因此可以将JOIN与一些精心设计的子查询结合使用:

SELECT a.cd_hs, EXTRACT(YEAR FROM a.dates), a.name_cnt, COALESCE(b.total_a, 0) as "Total A", COALESCE(c.total_b, 0) as "Total B"
FROM foo a
LEFT JOIN (
  SELECT b.cd_hs, b.name_cnt, EXTRACT(YEAR FROM b.dates), SUM(value_) as total_a
  FROM foo b
  WHERE b.cd_cnt NOT IN (1, 2)
  GROUP BY b.cd_hs, b.name_cnt, EXTRACT(YEAR from b.dates)
) b ON a.cd_hs = b.cd_hs AND a.name_cnt = b.name_cnt
LEFT JOIN (
  SELECT c.cd_hs, c.name_cnt, EXTRACT(YEAR FROM c.dates), SUM(value_) as total_b
  FROM foo c
  WHERE c.cd_cnt IN (1, 2)
  GROUP BY c.cd_hs, c.name_cnt, EXTRACT(YEAR from c.dates)
) c ON a.cd_hs = c.cd_hs AND a.name_cnt = c.name_cnt

这种特殊的解决方案易于阅读,可以使您获得正确的最终结果,但很可能无法以当前形式进行扩展。

结果:

| cd_hs | date_part | name_cnt | Total A | Total B |
|-------|-----------|----------|---------|---------|
|     1 |      2018 |      aaa |       0 |      90 |
|     1 |      2018 |      bbb |       0 |     220 |
|     1 |      2018 |      ccc |     100 |       0 |
|     1 |      2018 |      aaa |       0 |      90 |
|     1 |      2018 |      bbb |       0 |     220 |
|     1 |      2018 |      ccc |     100 |       0 |

SQLFiddle