简体   繁体   English

麻烦“过度划分”

[英]troubles on “over partition by”

I have to make a change to a pre-existing code (java) that interfaces with a DB using a query of this type: 我必须对使用以下类型的查询与数据库接口的现有代码(java)进行更改:

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

since I am not allowed to make separate queries and associate the results by working java side or to overturn the query (otherwise I would have switched to the dear old "group by" and perhaps I'd have been able to obtain something even if with a certainly longer and more complicated trip) I added something like: 因为不允许我进行单独的查询并通过工作Java端或翻转查询来关联结果(否则,我将切换到亲爱的旧“ group by”,即使使用,我也可以获得一些信息)肯定是更长更复杂的旅程),我添加了以下内容:

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

it works, but the problem is that in this way I get, when to the same "id_ana" are associated both "usestate = 1" and "usestate = 3" a double line with the same "id_ana" and this is not admitted: I can instead add columns at will. 它起作用了,但是问题是这样,我得到了,当同一个“ id_ana”同时与“ usestate = 1”和“ usestate = 3”相关联时,双行与同一个“ id_ana”相关联,这是不允许的:我可以随意添加列。 so I'd like to do something like this: 所以我想做这样的事情:

    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

but I'm not able to find the right syntax! 但是我找不到正确的语法! (I'm a "javer", not a "SQLer" :-) ) (我是“ javer”,而不是“ SQLer” :-))

Use conditional aggregation: 使用条件聚合:

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;

I don't understand why you would be using select distinct for this query. 我不明白为什么您要在此查询中使用select distinct

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM