簡體   English   中英

Tableau 中用於 CTE 查詢的初始 SQL

[英]Initial SQL for CTE query in Tableau

我正在嘗試運行以下 SQL 查詢

WITH Tap AS (SELECT DISTINCT 
    account_id,
    MONTH(t_start) AS month,
    DAY(t_start) AS day
FROM knowledge_repeat)
SELECT DISTINCT 
    account_id, 
    COUNT(account_id) as 'Unique',
    CASE
        WHEN COUNT(account_id) > 10 THEN 'Super Loyal'
        WHEN COUNT(account_id) > 5 AND COUNT(account_id) < 10 THEN 'Semi Loyal'
        WHEN COUNT(account_id) > 2 AND COUNT(account_id) < 5 THEN 'Tried It'
        WHEN COUNT(account_id) = 1 THEN 'Tried it once'
        ELSE 'Crazy Keen'
    END AS 'Loyalty Rating'
FROM Tap
GROUP BY account_id

但是得到以下錯誤

[MySQL][ODBC 8.0(w) Driver][mysqld-5.7.25-google-log]您的 SQL 語法有錯誤; 檢查與您的 MySQL 服務器版本相對應的手冊,以在第 1 行的“Tap AS (SELECT DISTINCT account_id, MONTH(t_start) AS month, DAY(t_start) AS”附近使用正確的語法 Initial SQL 錯誤。檢查語法是否為正確,並且您對請求的數據庫具有訪問權限。

我不明白為什么 - 它在 SSMS 和各種論壇上運行良好,我讀過 CTE 查詢應該在 Tableau 的 Initial SQL 部分中運行。

任何幫助表示贊賞!

您正在運行的 MySQL 5.7,如錯誤消息中所示,不支持WITH子句(又名公用表表達式)。 此功能僅在 8.0 版中添加。

對於您的查詢,您可以簡單地將 CTE 轉換為子查詢。 但是我仍然懷疑您的代碼可以大大簡化(當然,假設它當前在某些非 MySQL 數據庫上產生了您想要的結果)。

這是一個鏡頭:

select 
    account_id,
    cnt `Unique`,
    case
        when cnt > 10 then `Super Loyal`
        when cnt > 5  then `Semi Loyal`
        when cnt > 2  then `Tried It`
        when cnt = 1  then `Tried it once`
        else `Crazy Keen`
    end as `Loyalty Rating`
from (
    select
        account_id,
        count(distinct month(t_start), month(t_day)) as cnt
    from knowledge_repeat
    group by account_id
) t

理由:

  • this counts distinct month/day tuples per account_id (which seems to be the purpose of your nested select s), relying on a MySQL extension to the SQL standard which allows tuples in count(distinct) - we could also phrase this as count(distinct date_format(t_start, '%m-%d')) as cnt

  • 我使用一個子查詢只是出於懶惰,在case表達式中一次又一次地鍵入相同的聚合 function,但這里並不嚴格需要

  • case表達式按順序執行 - 因此無需指定條件的上限,因為它們已被前面的分支覆蓋

  • 您需要使用反引號來引用標識符而不是單引號

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM