我試圖自定義ORDER BY子句,以便'其他公司'總是最後。我不確定這裏有什麼問題。這是我所有的代碼。 WHERE子句看起來可能是多餘的,但這是因爲參數被宏代碼替換,這個SQL字符串被上傳到不同的日期和狀態。別擔心。我之前已經完成了這項工作,以處理不同的情況,我訂購了一切,但沒有訂購兩列。輸出說ORDER BY子句中的'AmountOfClaims'不是一個有效的列。有人能幫我嗎?通過自定義CASE的SQL順序當訂購
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
根本不是一個重複的問題。 – mattz608
確切地說你的問題。你嘗試使用'[AmountOfClaims]'而不是'COUNT(co。[CompanyName])'這是一個'計算列',而不是'WHERE'你試圖在'ORDER BY'上使用它' –