我會通過創建一個未定貨的子查詢來解決這個問題,其中我明確指出每個3個子查詢中每個等級的值。然後,我通過rank字段排序外部查詢。
下面的查詢將頂部的所有1,然後是2和3進行分組。假設你想先按人進行分組,你可以列出任何可以唯一標識該人的第一個字段。例如:「ORDER BY EmployerNo,Rank」。
此外,如果您不希望rank字段出現在輸出中,只是明確指出在外部查詢中選擇的字段而不是下面使用的「SELECT *」。
SELECT *
FROM(
SELECT 1 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "General")
OR (Role = "Services" and License = "Services")
OR (Role = "Admin" and License = "Admin")
UNION
SELECT 2 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Services")
OR (Role = "Services" and License = "General")
UNION
SELECT 3 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Admin")
OR (Role = "Services" and License = "Admin")
OR (Role = "Admin" and License = "Services")
OR (Role = "Admin" and License = "General")
) as a
ORDER BY Rank
編輯:添加請求的變化以僅報告每個員工和許可證的最高排名記錄。所以,我從早些時候就把自己的查詢加入自己,並做了一些小改動。更改是使查詢成爲彙總查詢,其中只報告每個許可證和員工的最高排名。 (我猜的是員工領域的名字)。當我們內部連接這些查詢時,我們會報告原始查詢中與MaxRank,許可證#和員工#匹配的所有字段。
SELECT a.*
FROM(
SELECT 1 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "General")
OR (Role = "Services" and License = "Services")
OR (Role = "Admin" and License = "Admin")
UNION
SELECT 2 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Services")
OR (Role = "Services" and License = "General")
UNION
SELECT 3 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Admin")
OR (Role = "Services" and License = "Admin")
OR (Role = "Admin" and License = "Services")
OR (Role = "Admin" and License = "General")
) as a
INNER JOIN (
SELECT Min(rank) as maxrank, License, employee
FROM(
SELECT 1 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "General")
OR (Role = "Services" and License = "Services")
OR (Role = "Admin" and License = "Admin")
UNION
SELECT 2 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Services")
OR (Role = "Services" and License = "General")
UNION
SELECT 3 as rank, *
FROM YourTable
WHERE (Role = "General" and License = "Admin")
OR (Role = "Services" and License = "Admin")
OR (Role = "Admin" and License = "Services")
OR (Role = "Admin" and License = "General")
) as a
GROUP BY License, employee
) as b on a.rank = b.maxrank and a.License = b.License and a.employee = b.employee
ORDER BY Rank
編輯#2:改變最大到最小
這查詢不MS訪問工作。 –
@GordonLinoff - 看起來對我來說......我錯過了什麼? – jleach
@ jdl134679。 。 。子查詢中的'union'。 –