麻烦“过度划分”

时间:2019-04-11 10:07:11

标签: sql window-functions

我必须使用以下类型的查询来更改与数据库连接的现有代码(java):

select distinct
  u.id_anauser,
  u.usestate,
  count(*) over (partition by u.usestate , id_anauser) cnt
from
  services u

由于不允许我进行单独的查询并通过工作Java端或翻转查询来关联结果(否则,我将切换到亲爱的旧“ group by”,也许我可以获得一些东西)即使行程肯定更长且更复杂),我也添加了类似的内容:

...
where (
u.usestate = 1
or
u.usestate = 3)

它可以工作,但是问题是这样我可以得到,何时将相同的“ id_ana”与“ usestate = 1”和“ usestate = 3”相关联,将双行与相同的“ id_ana”相关联,不承认:我可以改为随意添加列。 所以我想做这样的事情:

    select distinct
      u.id_anauser,
      u.usestate,
      count(*) over (partition by u.usestate = 1 , id_anauser) cnt1,
      count(*) over (partition by u.usestate = 3 , id_anauser) cnt2
    from
      services u

但是我找不到正确的语法! (我是“ javer”,而不是“ SQLer” :-))

1 个答案:

答案 0 :(得分:0)

使用条件聚合:

select distinct
       u.id_anauser,
       u.usestate,
       sum(case when u.usestate = 1 then 1 else 0 end)  over (partition by id_anauser) as cnt1,
       sum(case when u.usestate = 3 then 1 else 0 end)  over (partition by id_anauser) as cnt3
from services u;

我不明白您为什么要为此查询使用select distinct