sqlite 在SQL中将一个表的行连接到另一个表的列

8fq7wneg  于 2023-02-16  发布在  SQLite
关注(0)|答案(1)|浏览(160)

I have the following two tables in SQLite:
transactions:
| ID | Department |
| ------------ | ------------ |
| 1 | IT |
| 2 | Customer Service |
| 3 | Cleaning |
standards:
| IT | Customer Service | Cleaning |
| ------------ | ------------ | ------------ |
| 9.12 | 17.8 | 24.86 |
I want to join these two tables so the numbers in the second table become rows in my first table based on the matching value in the second table. The resulting table would look like this:
| ID | Department | Standard |
| ------------ | ------------ | ------------ |
| 1 | IT | 9.12 |
| 2 | Customer Service | 17.8 |
| 3 | Cleaning | 24.86 |
How can I join these, as I'm using the rows of one table and the columns of another?

nfg76nw0

nfg76nw01#

您需要表的CROSS连接和CASE表达式来选择适当的标准:

SELECT t.*,
       CASE t.Department
         WHEN 'IT' THEN s.IT
         WHEN 'Customer Service' THEN s.`Customer Service`
         WHEN 'Cleaning' THEN s.Cleaning
       END AS Standard
FROM transactions t JOIN standards s;

请参见demo

相关问题