[英]Assign values based on priority in sql
我有一個名稱表,其值如下:
Designation Priority
--------------------------
President 1
Founder 1
managing director 2
creative director 3
ceo 3
ict director 4
dpo 5
school director 6
和員工表:
Name Designation
-----------------
john president / school director
ralph ict director / dpo
ron Managing Director / Founder
rex Ceo/Creative Director
rick ceo/president
nick Founder / Managing Director
我期待的輸出是這樣的:
john president
ralph ict director
ron founder
rick president
nick founder
結果集中唯一比相鄰名稱具有更高等級的名稱。
在 SQL 中甚至可能出現這種類型的問題還是我必須使用 Python? 我使用的是 SQL Server 2019。 Employee 表中的 Designation 列的值具有以“/”分隔的名稱。
您正在考慮您的關系數據庫錯誤。 您實際上將需要 3 張桌子。
employee
+-------------------+------------+
| employee_id | name |
+-------------------+------------+
| 1 | John |
| 2 | Jane |
+-------------------+------------+
designation
+----------------------+-------------------------+----------------+
| designation_id | designation_name | priority |
+----------------------+-------------------------+----------------+
| 1 | president | 1 |
| 2 | school director | 1 |
| 3 | ict director | 2 |
+----------------------+-------------------------+----------------+
designation_to_employee
+---------+---------------------+-------------------+
| id | designation_id | employee_id |
+---------+---------------------+-------------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 2 |
+---------+---------------------+-------------------+
使用這三個表,無需在表內進行分隔。您可以為每個員工指定多個名稱——然后您可以按所述名稱進行排序。
IE
SELECT a.name, c.designation_name from employee a
LEFT JOIN designation_to_employee b
ON a.employee_id = b.employee_id
LEFT JOIN designation c
ON b.designation_id = c.designation_id
ORDER BY c.priority ASC
當然,如果您不希望 John 兩次出現在結果中,因為他是校長和學校主任,您可以按GROUP BY a.employee_id
或類似的內容進行GROUP BY a.employee_id
……這應該足以讓您順利進行。 如果您想要 John 的所有名稱,但在一行中,您將不得不使用NESTED SELECT
與CONCAT
結合使用,這遠遠超出了本 OP 的范圍,如果您是這樣,則需要成為一個關於 SO 的新問題正在嘗試。 首先正確設置您的數據庫,然后嘗試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.