我需要帮助来转换表格上的数据,将一系列列减少到一列。下面是一个例子:
Frequency_1 integer,
Frequency_2 integer,
Frequency_3 integer,
Frequency_4 integer,
这些列当前包含1或0.只有一列将保留1。
新列应定义为
Frequency integer
此新列应保存1到4之间的值,具体取决于哪些旧列的值为1。
你能建议一个SQL命令来完成这个吗?
答案 0 :(得分:3)
如果你愿意,你可以想出更复杂的东西,但为什么不这样做呢?
SELECT Frequency_1 +
(Frequency_2 * 2) +
(Frequency_3 * 3) +
(Frequency_4 * 4) AS Frequency
要实际进行更改,您可以先创建列,更新新列中的值,然后删除旧列。
答案 1 :(得分:3)
SELECT
CASE WHEN Frequency_1 = 1 THEN 1
WHEN Frequency_2 = 1 THEN 2
WHEN Frequency_3 = 1 THEN 3
WHEN Frequency_4 = 1 THEN 4
ELSE 0 END AS Frequency
FROM TABLE
答案 2 :(得分:1)
update table_name
set frequency =
case when frequency_1 = 1 then 1 else
case when frequency_2 = 1 then 2 else
case when frequency_3 = 1 then 3 else
case when frequency_4 = 1 then 4
end
end
end
end
答案 3 :(得分:1)
像这样:
select Frequency =
Frequency_1 * 1 +
Frequency_2 * 2 +
Frequency_3 * 3 +
Frequency_4 * 4
from ATable
或者这个:
select Frequency = case
when Frequency_1 = 1 then 1
when Frequency_2 = 1 then 2
when Frequency_3 = 1 then 3
when Frequency_4 = 1 then 4
else 0
end
from ATable