SQL订购时按自定义情况排序

时间:2016-08-16 18:28:53

标签: sql sql-server database sql-order-by case-when

我正在尝试自定义ORDER BY子句,以便“其他公司”始终排在最后。我不确定这里有什么问题。这是我的所有代码。 WHERE子句似乎是多余的,但这是因为参数被宏代码替换,其中上传的SQL字符串根据日期和状态以不同方式填充。别担心。我之前已经做过这种情况,因为我订购了所有的东西但不是两个不同的列。输出显示ORDER BY子句中的“AmountOfClaims”不是有效列。有人能帮助我吗?

SELECT 
    CASE 
       WHEN co.[CompanyName] != '' 
          THEN co.CompanyName 
          ELSE 'Unspecified Companies' 
    END AS CompanyName, 
    COUNT(co.[CompanyName]) AS [AmountOfClaims]
FROM
    (SELECT 
         CASE 
            WHEN [Claims].[CompanyName] IN (SELECT TOP 10 [Claims].[CompanyName]
                                            FROM [Claims]
                                            WHERE Claims.[HousingRequested] >= '2016-08-02'
                                              AND Claims.[HousingRequested] <= '2016-08-16'
                                              AND (Claims.[State] = NULL OR Claims.[State] >= CASE WHEN NULL IS NULL THEN ' ' ELSE 'ZZZZ' END)
                                            GROUP BY [Claims].[CompanyName]
                                            ORDER BY COUNT([Claims].[CompanyName]) DESC)
               THEN [Claims].[CompanyName] 
               ELSE 'Other Companies' 
         END AS [CompanyName]
     FROM 
         [Claims] 
     WHERE 
         Claims.[HousingRequested] >= '2016-08-02'
         AND Claims.[HousingRequested] <= '2016-08-16'
         AND (Claims.[State] = NULL OR Claims.[State] >= CASE WHEN NULL IS NULL THEN ' ' ELSE 'ZZZZ' END)
    ) AS co
GROUP BY 
    co.[CompanyName]
ORDER BY 
    CASE 
       WHEN [CompanyName] = 'Other Companies' 
          THEN 9999 
          ELSE [AmountOfClaims] 
    END DESC

1 个答案:

答案 0 :(得分:3)

您可以将当前查询用作派生表或CTE,或者只使用COUNT中的ORDER BY

SELECT 
    CASE WHEN co.[CompanyName] != '' THEN co.CompanyName ELSE 'Unspecified Companies' END AS CompanyName, 
    COUNT(co.[CompanyName]) AS [AmountOfClaims]
FROM
    ( SELECT CASE WHEN [Claims].[CompanyName] IN

            ( SELECT TOP 10 [Claims].[CompanyName]
            FROM [Claims]
                WHERE Claims.[HousingRequested] >= '2016-08-02'
                AND Claims.[HousingRequested] <= '2016-08-16'
                AND (Claims.[State] = NULL OR Claims.[State] >= CASE WHEN NULL IS NULL THEN ' ' ELSE 'ZZZZ' END)

            GROUP BY [Claims].[CompanyName]
            ORDER BY COUNT([Claims].[CompanyName]) DESC )

        THEN [Claims].[CompanyName] ELSE 'Other Companies' END AS [CompanyName]

    FROM [Claims] 
        WHERE Claims.[HousingRequested] >= '2016-08-02'
        AND Claims.[HousingRequested] <= '2016-08-16'
        AND (Claims.[State] = NULL OR Claims.[State] >= CASE WHEN NULL IS NULL THEN ' ' ELSE 'ZZZZ' END)
    ) AS co

GROUP BY co.[CompanyName]
ORDER BY CASE WHEN [CompanyName] = 'Other Companies' THEN 9999 ELSE COUNT(co.[CompanyName]) END DESC;