SQL - 如何汇总/聚合表中的某些行

时间:2018-05-15 13:48:36

标签: sql postgresql

我有一个表t看起来像这样(这本身就是长SQL查询的结果):

    ID     | Name     | Active     | Sales
----------------------------------------------
    1        Amy        t            50
    2        Bill       f            4
    3        Chip       t            127
    4        Dana       t            543
    5        Eve        f            20

我正在寻找非活动用户("Active" = f)的组合,以便最终得到如下结果表:

    ID     | Name     | Active     | Sales
----------------------------------------------
    1        Amy        t            50
    3        Chip       t            127
    4        Dana       t            543
    0        -          f            24

有没有办法在不重复初始查询的情况下执行此操作来获取该表?

4 个答案:

答案 0 :(得分:3)

这是一个简单的方法:

select id, name, active, sales
from t
where active
union all
select 0, NULL, f, sum(sales)
from t
where not active;

如果这是复杂视图的结果,您可能不希望引用它两次。如果是这样,您可以使用聚合:

select (case when active then id end) as id,
       (case when active then name end) as name,
       active,
       sum(sales) as sales
from t
group by (case when active then id end),
         (case when active then name end) as name,
         active;

答案 1 :(得分:3)

使用另一个带有布尔值的表进行采样(使用kvazi int,boolean和kvazi文本属性)((与上面不同的是没有联合,只有一个案例))(((使用sum因为我认为这是什么你想要 - 聚合一个案例))):

t=# select
  case when not rolsuper then '-' else rolname::text end
, rolsuper
, sum(oid::text::int)
from pg_roles
group by case when not rolsuper then '-' else rolname::text end,rolsuper;
 rolname  | rolsuper |  sum
----------+----------+--------
 -        | f        | 144394
 vao      | t        |  16555
 postgres | t        |     10
(3 rows)

所以对你来说应该像:

select
      case when not active then 0 else id end
    , case when not active then '-' else name end
    , active
    , sum(sales)
    from t
    group by 
      case when not active then 0 else id end
    , case when not active then '-' else name end
    , active;

答案 2 :(得分:2)

SELECT ID
    ,Name
    ,Active
    ,Sales
FROM my TABLE
WHERE Active = 't'

UNION

SELECT 0
    ,''
    ,Active
    ,COUNT(Sales)
FROM my TABLE
WHERE Active = 'f'
GROUP BY Active

答案 3 :(得分:0)

这里没有工会:

select IIF(Active = 'f', 0, ID) ID, IIF(Active = 'f', '-', Name) Name, Active, SUM(Sales) Sales
from t
group by IIF(Active = 'f', 0, ID), IIF(Active = 'f', '-', Name), Active