我有 5 列对应于问答游戏数据库中的答案 - 对、错 1、错 2、错 3、错 4
我想返回所有可能的答案而不重复。我希望在不使用临时表的情况下完成此操作。是否可以使用类似的东西?:
select c1, c2, count(*)
from t
group by c1, c2
但这会返回 3 列。我想要一列不同的答案。
谢谢你的时间
这应该为您提供表中所有不同的值。我假设您想添加 where 子句以仅针对特定问题进行选择。但是,此解决方案需要 5 个子查询,如果您的表很大,可能会很慢。
SELECT DISTINCT(ans) FROM (
SELECT right AS ans FROM answers
UNION
SELECT wrong1 AS ans FROM answers
UNION
SELECT wrong2 AS ans FROM answers
UNION
SELECT wrong3 AS ans FROM answers
UNION
SELECT wrong4 AS ans FROM answers
) AS Temp
SELECT DISTINCT(ans) FROM (
SELECT right AS ans FROM answers
UNION
SELECT wrong1 AS ans FROM answers
UNION
SELECT wrong2 AS ans FROM answers
UNION
SELECT wrong3 AS ans FROM answers
UNION
SELECT wrong4 AS ans FROM answers
) AS Temp
DISTINCT 是多余的,因为 UNION 不会返回所有列都相同的行。(如果您想要重复,或者如果您知道不存在重复,请使用 UNION ALL 以获得更快的性能)
这将为您提供一个包含所有答案的列表。如果您在单个列中有多个相同答案的副本,您仍然会有重复。
如果您使用 UNION,则不应该是这种情况,仅当您使用 UNION ALL
SELECT [value] INTO #TEMP
FROM
(
SELECT [value] = 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 1
) AS X
(4 row(s) affected)
SELECT [value]
FROM #TEMP
value
-----------
1
2
3
1
(4 row(s) affected)
SELECT [value]
FROM #TEMP
UNION
SELECT [value]
FROM #TEMP
value
-----------
1
2
3
(3 row(s) affected)
我在上面提供了一个答案。
但是,我想出了一个更好的方法来使用 UNPIVOT。
SELECT DISTINCT(ans)
FROM (
SELECT [Name], ANS
FROM (
SELECT right, wrong1, wrong2, wrong3, wrong4
FROM answers
) AS PVT
UNPIVOT
(ans FOR [Name] IN (right, wrong1, wrong2, wrong3, wrong4)) AS UNPVT
) AS OUTPUT;
您可以在内部子查询中提供任何 WHERE 子句:
SELECT DISTINCT(ans)
FROM (
SELECT [Name], ANS
FROM (
SELECT right, wrong1, wrong2, wrong3, wrong4
FROM answers
WHERE (...)
) AS PVT
UNPIVOT
(ans FOR [Name] IN (right, wrong1, wrong2, wrong3, wrong4)) AS UNPVT
) AS OUTPUT;
好吧,您可以使用 UNION 并运行 5 个选择语句,表中的每一列一个。它看起来像这样:
SELECT right FROM answers
UNION
SELECT wrong1 FROM answers
UNION
SELECT wrong2 FROM answers
UNION
SELECT wrong3 FROM answers
UNION
SELECT wrong4 FROM answers
这将为您提供一个包含所有答案的列表。如果您在单个列中有多个相同答案的副本,您仍然会有重复。
“正确,错误1,错误2,错误3,错误4”的列表示您的数据库设计错误。一般来说,列名上的数字或字母后缀应该是重新考虑问题的危险信号。
正如您所观察到的,您的设计要求您设法解决典型的数据缩减问题。
这是你想要的吗?
select distinct c1 from t
在MySQL
AND中MS SQL
:
SELECT
CASE
WHEN which = 1 THEN c1
WHEN which = 2 THEN c2
WHEN which = 3 THEN c3
WHEN which = 4 THEN c4
WHEN which = 5 THEN c5
END AS answer,
which
FROM mytable, (
SELECT 1 AS which
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
) w
对于Oracle
,添加FROM DUAL
到每个数字选择。
这是准确的答案。
SELECT (ans) FROM (
SELECT correct AS ans FROM tGeoQuiz
UNION
SELECT wrong1 AS ans FROM tGeoQuiz
UNION
SELECT wrong2 AS ans FROM tGeoQuiz
UNION
SELECT wrong3 AS ans FROM tGeoQuiz
UNION
SELECT wrong4 AS ans FROM tGeoQuiz
) AS Temp