我有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;