MariaDB,在“ GROUP BY 1,2”附近使用什么正确的语法?

时间:2019-05-06 23:32:17

标签: sql mariadb

我正在编写一个MariaDB查询,并遇到以下错误:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'GROUP BY 1,2
       ) x
       ) z
 WHERE user_period != 0
 ORDER BY 1,2
-- {"us' at line 42

以下是查询:

WITH 

users AS (
  SELECT id,
         onboarded_at
    FROM users
   WHERE onboarded_at <= NOW()
   GROUP BY 1
),

events AS (
  SELECT receiver_id,
         type,
         created_at
    FROM events 
   WHERE created_at <= NOW()
)
SELECT *
  FROM (
SELECT *,
       MAX(CASE WHEN user_period = 0 THEN retained_users ELSE NULL END) OVER (PARTITION BY "Signup Date") AS "New Users",

       retained_users/
          MAX(CASE WHEN user_period = 0 THEN retained_users ELSE NULL END) OVER (PARTITION BY "Signup Date") AS retention_rate,

       (LAG(retained_users) OVER (PARTITION BY "Signup Date" ORDER BY "Signup Date") - retained_users)/
          MAX(CASE WHEN user_period = 0 THEN retained_users ELSE NULL END) OVER (PARTITION BY "Signup Date") AS churn_rate,

       (LAG(retained_users) OVER (PARTITION BY "Signup Date" ORDER BY "Signup Date") - retained_users)/
          LAG(retained_users) OVER (PARTITION BY "Signup Date" ORDER BY "Signup Date") AS churn_rate_from_previous_period
  FROM (

SELECT (MONTH,u.onboarded_at) AS "Signup Date",
       (EXTRACT(YEAR FROM e.created_at) - EXTRACT(YEAR FROM u.onboarded_at)) * 12 + 
       (EXTRACT(MONTH FROM e.created_at) - EXTRACT(MONTH FROM u.onboarded_at)) - 
       CASE WHEN (CEILING(DATE_PART('day',f.created_at) - DATE_PART('day',u.onboarded_at))) < 0 THEN 1 ELSE 0 END AS user_period,
       COUNT(DISTINCT f.receiver_id) AS retained_users
  FROM users u
  JOIN events f
    ON e.receiver_id = u.id
 WHERE u.onboarded_at >= DATE_TRUNC(MONTH,NOW()) - INTERVAL '25 MONTH'
 GROUP BY 1,2
       ) x
       ) z
 WHERE user_period != 0
 ORDER BY 1,2

SQL错误没有帮助;我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

您的问题实际上出在查询的这一部分:

INTERVAL '25 MONTH'

正确的格式是

INTERVAL 25 MONTH

另一个问题是MariaDB没有DATE_TRUNC函数,因此假设它是用户定义的函数,具有参数MONTHNOW()。由于MONTH未加引号,因此假设它是列名,因此您将收到未知的列错误。要解决此问题,您可以替换

DATE_TRUNC(MONTH,NOW())

DATE_FORMAT(CURDATE(), '%Y-%m-01 00:00:00')

此外,由于MariaDB没有DATE_PART函数,因此您需要替换

DATE_PART('day', expression)

使用

DAY(expression)