postgresql—如何使用sql选择最后一个非直接源

2g32fytz  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(623)

我有以下接触点:

Session Number  Source
1               direct
2               social
3               paid
4               direct
5               direct
6               direct

我需要选择最后一个非直接来源…这是支付在这个例子(第3节)。
考虑到可能是直接的情况,然后直接显示。所以基本上我们需要和谷歌分析一样:最后的非直接归属。
什么sql代码可以做到这一点?

z3yyvxxp

z3yyvxxp1#

就你的例子来说,这应该管用

SELECT TOP 1 * FROM [Your_Table] 
WHERE Source <> 'direct'
ORDER BY [Session Number] DESC

类似问题
编辑1:

SELECT * FROM [Your_Table] 
WHERE 
--checking if anything else except 'direct' exists, if so, take the last one non direct
(EXISTS (SELECT * FROM [Your_Table] WHERE source <> 'direct') AND source <> 'direct') 
OR 
--if nothing except direct doesn't exist, just take the last row
NOT EXISTS (SELECT * FROM [Your_Table] WHERE source <> 'direct')
ORDER BY [session number] DESC
LIMIT 1;
7gs2gvoe

7gs2gvoe2#

我需要选择最后一个非直接来源…这是支付在这个例子(第3节)。
在postgres中,您将使用:

select t.*
from t
where Source <> 'direct'
order by session_number desc
limit 1;

而不是 limit ,也可以使用:

fetch first 1 row only

如果不需要筛选,可以使用:

select t.*
from t
where Source <> 'direct'
order by (source = 'direct') asc,  -- put last
         session_number desc
limit 1;

或者,如果只需要会话号,可以使用条件聚合:

select coalesce( max(session_number) filter (where source <> 'direct'),
                 max(session_number)
from t;

相关问题