简体   繁体   English

转换 CTE SQL 语句以符合 Tableau 标准

[英]Converting CTE SQL statement to fit Tableau standards

I am creating a custom query in Tableau, but it doesn't seem to support CTE statements.我正在 Tableau 中创建自定义查询,但它似乎不支持 CTE 语句。

with cte (domain, ip_addr, time_col) as
(
select 'Google',101,'2020-03-31 14:55:37'
UNION select 'Google',101,'2020-03-31 14:56:12'
union select 'Facebook',101,'2020-03-31 14:57:36'
union select 'Amazon',101,'2020-03-31 14:57:45'
)

select
domain,
ip_addr,
time_col,
sum(switches) over (partition by ip_addr) -1
from (
select *,
case when lag (domain) over (partition by ip_addr order by time_col) = domain then 0 else 1 end as switches
    
from cte
) t

How can I modify the above query to remove the CTE statement but keep the same results?如何修改上述查询以删除 CTE 语句但保持相同的结果?

Honestly, it seems like you would be better off with a VALUES table construct, rather than an expensive UNION (not even UNION ALL ) query:老实说,使用VALUES表结构而不是昂贵的UNION (甚至不是UNION ALL )查询似乎会更好:

SELECT DT.domain,
       DT.ip_addr,
       DT.time_col,
       SUM(DT.switches) OVER (PARTITION BY DT.ip_addr) - 1 AS ColumnAliasGoesHere
FROM (SELECT V.domain,
             V.ip_addr,
             V.time_col,
             CASE WHEN LAG(V.domain) OVER (PARTITION BY V.ip_addr ORDER BY V.time_col) = V.domain THEN 0 ELSE 1 END AS switches
      FROM (VALUES ('Google', 101, '2020-03-31 14:55:37'),
                   ('Google', 101, '2020-03-31 14:56:12'),
                   ('Facebook', 101, '2020-03-31 14:57:36'),
                   ('Amazon', 101, '2020-03-31 14:57:45')) V (domain, ip_addr, time_col) ) DT;
select
 domain,
 ip_addr,
 time_col,
 sum(switches) over (partition by ip_addr) -1
from (
      select *,
         case when lag (domain) over (partition by ip_addr order by time_col) = domain then 0 else 1 end as switches

      from 
       (
           select 'Google',101,'2020-03-31 14:55:37'
           UNION select 'Google',101,'2020-03-31 14:56:12'
           union select 'Facebook',101,'2020-03-31 14:57:36'
           union select 'Amazon',101,'2020-03-31 14:57:45'
      )cte(domain, ip_addr, time_col)
 ) t

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

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