Reputation: 97
I have a sample data, which I want to sort. If User is 1,then sort views in descending, otherwise if User is not 1,then sort normally. I have written below sql,and I am getting required result. My Question is Why and How it works?
with data as (
select 2 as User, 1 as Views UNION ALL
select 1,3 UNION ALL
select 4,1 UNION ALL
select 1,5 UNION ALL
select 1,6 UNION ALL
select 2,6 UNION ALL
select 7,2 UNION ALL
select 8,3 UNION ALL
select 3,9
)
select ARRAY_AGG(struct(User,Views) order by if(User=1,1,0) desc ,Views desc )
from data
Can Anyone explain me,how its working? Image 1 Image 2
Upvotes: 2
Views: 902
Reputation: 172993
Can Anyone explain me,how its working?
I think below is the simplest way to explain/show what is happening here
Consider below slightly modified/simplified example - I eliminated aggregation to focus on ordering aspect only
with data as (
select 2 as user, 1 as views union all
select 1,3 union all
select 4,1 union all
select 1,5 union all
select 1,6 union all
select 2,6 union all
select 7,2 union all
select 8,3 union all
select 3,9
)
select *, if(user=1,1,0) sort
from data
order by sort desc, views desc
output of above is
I don't think you have any doubts why above result is as is - it is just straightforward!!
Now - if you use if(user=1,100,0)
- you get
Obviously, exactly same output (in terms of ordering) and I still don't think you have any doubts why it is as it is
So, finally to streamline query - users (or at least power users) would use the shortcut - instead of introducing sort
column to use in order by
- they would move this into order by
itself
Hope this is clear now for you!
Upvotes: 1