加入表

时间:2018-06-06 03:24:07

标签: sql sql-server

我在下面的代码目前有效,但在COUNT之后添加ORDER BY后,它给了我错误

  

无效的列名'Answers'

SELECT  Test.SOLUTION_NOT_FOUND, 
        Test.SEARCH_TEST, 
        Test.KEYWORD as Search_Words, 
        Test2.Answers_for_exam AS Answers
FROM    Test 
INNER JOIN  Test2 ON Test.TEST_NUMBER = Test2.TEST_NUMBER
WHERE SOLUTION_NOT_FOUND = 1
ORDER BY COUNT(Answers) DESC

我在第一行尝试了COUNT(Test2.Answers_for_exam) AS Answers但也提供了相同的错误消息。 我是否也可以不显示SOLUTION_NOT_FOUND列。我只是在那里添加它才能看到结果,但不需要看到它。

在Answers列下有重复的字符串。我想按大多数字符串排序。例如:汽车,汽车,纸张,岩石,纸张,纸张。我希望纸张首先返回,然后是汽车然后摇滚,因为纸张有3个计数,汽车有2个计数,摇滚只有1个计数(假设只有3个唯一的字符串)。如果我做ORDER BY Answers DESC,他们将按字母顺序排列。

3 个答案:

答案 0 :(得分:1)

使用COUNT(*) OVER()窗口函数执行所需的计数,然后按顺序排序

SELECT  Test.SOLUTION_NOT_FOUND, 
        Test.SEARCH_TEST, 
        Test.KEYWORD as Search_Words, 
        Test2.Answers_for_exam AS Answers,
        COUNT(*) OVER (PARTITION BY Test2.Answers_for_exam) AS AnswerCount
FROM    Test 
INNER JOIN  Test2 ON Test.TEST_NUMBER = Test2.TEST_NUMBER
WHERE SOLUTION_NOT_FOUND = 1
ORDER BY AnswerCount DESC

答案 1 :(得分:1)

您应该在单独的列(此处为cnt)中跟踪答案数量,然后按照下面的顺序进行排序

SELECT 
    SOLUTION_NOT_FOUND,
    SEARCH_TEST,
    Search_Words,
    Answers
FROM
(
SELECT  Test.SOLUTION_NOT_FOUND, 
        Test.SEARCH_TEST, 
        Test.KEYWORD as Search_Words, 
        Test2.Answers_for_exam AS Answers,
        COUNT(Test2.Answers_for_exam) over ( order by (select 1)) as cnt
FROM    Test 
INNER JOIN  Test2 ON Test.TEST_NUMBER = Test2.TEST_NUMBER
WHERE SOLUTION_NOT_FOUND = 1
)T 
ORDER BY cnt DESC

你也可以使用下面的分组

SELECT  Test.SOLUTION_NOT_FOUND, 
        Test.SEARCH_TEST, 
        Test.KEYWORD as Search_Words, 
        Test2.Answers_for_exam AS Answers
FROM    Test 
INNER JOIN  Test2 ON Test.TEST_NUMBER = Test2.TEST_NUMBER
WHERE SOLUTION_NOT_FOUND = 1
GROUP BY 
        Test.SOLUTION_NOT_FOUND, 
        Test.SEARCH_TEST, 
        Test.KEYWORD as Search_Words, 
        Test2.Answers_for_exam
ORDER BY COUNT(Test2.Answers_for_exam) DESC

答案 2 :(得分:1)

您可以在order by中使用窗口功能。所以,我想你想要:

SELECT Test.SOLUTION_NOT_FOUND, 
       Test.SEARCH_TEST, 
       Test.KEYWORD as Search_Words, 
       Test2.Answers_for_exam AS Answers
FROM Test INNER JOIN
     Test2
     ON Test.TEST_NUMBER = Test2.TEST_NUMBER
WHERE SOLUTION_NOT_FOUND = 1
ORDER BY COUNT(*) OVER (PARTITION BY Test2.Answers_for_exam) DESC;

这应该是实现目标的最简单方法。