添加 WHERE 后出现语法错误。 R 中的 SQLite
Syntax error after adding WHERE. SQLite in R
我有一个航班数据,包括出发地、目的地和月份。
我试图在一年中的一个月内获得从起点到终点的航班频率。
我完成了:
dbGetQuery(conn,"
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
")
首先结合数据库中的 Origin 和 Dest,然后计算它的频率以获得输出:
Month Freq OriDes
1 1 123 ABE-ATL
2 2 140 ABE-ATL
3 3 117 ABE-ATL
4 4 112 ABE-ATL
5 5 111 ABE-ATL
6 6 120 ABE-ATL
7 7 113 ABE-ATL
8 8 124 ABE-ATL
9 9 94 ABE-ATL
10 10 119 ABE-ATL
11 11 116 ABE-ATL
12 12 124 ABE-ATL
13 6 1 ABE-AVP
14 1 66 ABE-CLE
15 2 72 ABE-CLE
16 3 99 ABE-CLE
17 4 89 ABE-CLE
18 5 91 ABE-CLE
19 6 97 ABE-CLE
20 7 92 ABE-CLE
但是因为这是一个大数据我希望过滤并且只处理Freq > 500。所以我尝试了:
dbGetQuery(conn,"
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
WHERE Freq > 500
")
但我会得到一个错误:
Error: near "WHERE": syntax error
有人可以向我解释我做错了什么吗?
正如评论中所建议的:
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
HAVING COUNT(OriDes) > 500
您可以直接在 table 中进行聚合而无需子查询,您只需要一个 HAVING
子句来过滤聚合结果,而不是 WHERE
子句来过滤聚合结果table聚合前:
SELECT Month,
COUNT(*) AS Freq,
Origin || '-' || Dest AS OriDes
FROM flights
GROUP BY Month, OriDes
HAVING Freq > 500;
请注意,由于您在 GROUP BY
子句中使用了 OriDes
,因此没有必要在 COUNT()
中使用它。你可以用 COUNT(*)
.
来计算
我有一个航班数据,包括出发地、目的地和月份。 我试图在一年中的一个月内获得从起点到终点的航班频率。
我完成了:
dbGetQuery(conn,"
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
")
首先结合数据库中的 Origin 和 Dest,然后计算它的频率以获得输出:
Month Freq OriDes
1 1 123 ABE-ATL
2 2 140 ABE-ATL
3 3 117 ABE-ATL
4 4 112 ABE-ATL
5 5 111 ABE-ATL
6 6 120 ABE-ATL
7 7 113 ABE-ATL
8 8 124 ABE-ATL
9 9 94 ABE-ATL
10 10 119 ABE-ATL
11 11 116 ABE-ATL
12 12 124 ABE-ATL
13 6 1 ABE-AVP
14 1 66 ABE-CLE
15 2 72 ABE-CLE
16 3 99 ABE-CLE
17 4 89 ABE-CLE
18 5 91 ABE-CLE
19 6 97 ABE-CLE
20 7 92 ABE-CLE
但是因为这是一个大数据我希望过滤并且只处理Freq > 500。所以我尝试了:
dbGetQuery(conn,"
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
WHERE Freq > 500
")
但我会得到一个错误:
Error: near "WHERE": syntax error
有人可以向我解释我做错了什么吗?
正如评论中所建议的:
SELECT
Month AS Month,
COUNT(OriDes) AS Freq,
OriDes
FROM(
SELECT Origin || '-' || Dest AS OriDes,
Month AS Month
FROM flights
)
GROUP BY OriDes, Month
HAVING COUNT(OriDes) > 500
您可以直接在 table 中进行聚合而无需子查询,您只需要一个 HAVING
子句来过滤聚合结果,而不是 WHERE
子句来过滤聚合结果table聚合前:
SELECT Month,
COUNT(*) AS Freq,
Origin || '-' || Dest AS OriDes
FROM flights
GROUP BY Month, OriDes
HAVING Freq > 500;
请注意,由于您在 GROUP BY
子句中使用了 OriDes
,因此没有必要在 COUNT()
中使用它。你可以用 COUNT(*)
.