I have to make a change to a pre-existing code (java) that interfaces with a DB using a query of this type:
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:
...
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. 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" :-) )
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.