我需要生成复杂的select语句,每次运行脚本时都会根据输入文件进行更改。
我有一个名单列表作为我的过滤器列表,我有一个select语句,已在另一个线程中向我建议。我不确定如何生成我需要的东西,而不是在谷歌接下来的6个小时拼凑它。
我需要为列表中的每个项目创建一个MAX(CASE ...行)。
list <- df$names
list:
1 square
2 ball
3 dog
4 triangle
5 hamster
6 circle
7 yellow
8 cat
suggested SELECT format:
SELECT
data.loc
, data.type
, MAX(CASE WHEN data.name = 'cat' THEN 1 ELSE 0 END) AS cat
, MAX(CASE WHEN data.name = 'hamster' THEN 1 ELSE 0 END) AS hamster
FROM
data
GROUP BY
data.loc
, data.type
我相信所需的输出将是:
SELECT
data.loc
, data.type
, MAX(CASE WHEN data.name = 'square' THEN 1 ELSE 0 END) AS square
, MAX(CASE WHEN data.name = 'ball' THEN 1 ELSE 0 END) AS ball
, MAX(CASE WHEN data.name = 'dog' THEN 1 ELSE 0 END) AS dog
, MAX(CASE WHEN data.name = 'triangle' THEN 1 ELSE 0 END) AS triangle
, MAX(CASE WHEN data.name = 'hamster' THEN 1 ELSE 0 END) AS hamster
, MAX(CASE WHEN data.name = 'circle' THEN 1 ELSE 0 END) AS circle
, MAX(CASE WHEN data.name = 'yellow' THEN 1 ELSE 0 END) AS yellow
, MAX(CASE WHEN data.name = 'cat' THEN 1 ELSE 0 END) AS cat
FROM
data
GROUP BY
data.loc
, data.type
我能想到的最简单的方法是
l <- list("Cat", "dog", "bird")
sqlqry <- "SELECT
data.loc
, data.type"
for (i in 1:length(l)) {
sqlqry <- paste0(sqlqry, sprintf(", MAX(CASE WHEN data.name = '%s' THEN 1 ELSE 0 END) AS %s",l[i], l[i]))
print(sqlqry)
}
sqlqry <- paste0(sqlry, "your where clause")