我想回答这个问题:
角色出现在第一个位置的频率与 字符串的第二个位置?
在Mysql上使用SQL查询。
但是我收到语法错误。
代码:
SELECT
onechar,
ASCII(onechar) as asciival,
COUNT(*) as cnt,
SUM(CASE WHEN pos = 1 THEN 1 ELSE 0 END) as pos_1,
SUM(CASE WHEN pos = 2 THEN 1 ELSE 0 END) as pos_2
FROM (
(SELECT
SUBSTRING(`city`, 1, 1) as onechar,
1 as pos
FROM `orders`
WHERE LEN(`city` >= 1 )
UNION ALL
(SELECT
SUBSTRING(`city`, 2, 1) as onechar,
2 as pos
FROM `orders`
WHERE LEN(`city` >= 2)
)
GROUP BY onechar
ORDER BY onechar
错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 靠近' GROUP BY onechar ORDER BY onechar LIMIT 0,30'在第1行
尝试了几种方法但没有成功。
任何人都可以解释一下这个问题吗?
答案 0 :(得分:0)
括号外观不正确,查询缺少派生表的别名。此外,因为mysql将布尔值评估为1或0,所以您可以简化sum
语句。试试这个:
SELECT onechar, ASCII(onechar) as asciival, COUNT(*) as cnt,
SUM(pos = 1) as pos_1,
SUM(pos = 2) as pos_2
FROM (
SELECT SUBSTRING(`city`, 1, 1) as onechar, 1 as pos
FROM `orders` WHERE LENGTH(`city`) >= 1
UNION ALL
SELECT SUBSTRING(`city`, 2, 1) as onechar, 2 as pos
FROM `orders` WHERE LENGTH(`city`) >= 2
) t
GROUP BY onechar
ORDER BY onechar
答案 1 :(得分:0)
你错过了一些结束括号。
FROM (
(SELECT
SUBSTRING(`city`, 1, 1) as onechar,
1 as pos
FROM `orders`
WHERE LEN(`city` >= 1 )
)
UNION ALL
(SELECT
SUBSTRING(`city`, 2, 1) as onechar,
2 as pos
FROM `orders`
WHERE LEN(`city` >= 2)
)
)