我正在尝试运行一个非常简单的CASE...WHEN
语句:
SELECT userid, sum(end_time-start_time)/60 AS timespent_minutes,
CASE WHEN webid = '324234' THEN 'CA'
ELSE 'Other' END AS storeloc
FROM time_spent_intervals
WHERE (ds = '2018-12-01')
GROUP BY userid, storeloc
但是我遇到以下错误:
错误:SYNTAX_ERROR
第6:38行:无法解析“ storeloc”列
答案 0 :(得分:4)
尝试在GROUP BY
中重复该表达式:
SELECT userid, sum(end_time-start_time)/60 AS timespent_minutes,
(CASE WHEN webid = '324234' THEN 'CA' ELSE 'Other' END) AS storeloc
FROM time_spent_intervals
WHERE ds = '2018-12-01'
GROUP BY userid, (CASE WHEN webid = '324234' THEN 'CA' ELSE 'Other' END) ;
尽管MySQL允许GROUP BY
使用列别名,但并非所有数据库都允许。我猜你不是真的在使用MySQL。
答案 1 :(得分:0)
SQL Server查询始终按以下顺序执行查询
FROM
WHERE
GROUP BY
HAVING
SELECT
ORDER BY
您已引用了GROUP BY中SELECT类中定义的列别名。但是GROUP BY将在SELECT语句之前执行。这就是错误的原因。以上建议的解决方案将满足您的需求。