2

我有 2 张桌子:

表格1

编号 | 姓名
-----------------------------------------
1 | 美国广播公司
2 | 定义

表2

table1id | nr_name | nr_val
-----------------------------------------
1 | 7 | 123
1 | 9 | 321
2 | 7 | 432


我需要什么 SQL 代码才能得到这个结果?

结果

编号 | 姓名 | NR7 | NR9
-----------------------------------------
1 | 美国广播公司 | 123 | 321
2 | 定义 | 第432章 0

nr_name 只能是 7 或 9 并且我不能更改 table2 的结构(我稍后会添加更多的 nr_name 类型)。

4

2 回答 2

1

尝试这个:

sELECT 
  t1.id,
  t1.name,
  MAX(CASE WHEN t2.nr_name = 7 THEN t2.nr_val END) AS 'nr7',
  MAX(CASE WHEN t2.nr_name = 9 THEN t2.nr_val END) AS 'nr9'
FROM table1 AS t1
INNER JOIN  table2 AS t2 ON t1.id = t2.table1id
WHERE t2.name IN (7, 9)
GROUP BY t1.id, t1.name
于 2013-04-28T10:31:44.640 回答
0
SELECT t1.id,t1.name,
       CASE WHEN t2.nr_name = 7 THEN t2.nr_val ELSE 0 END AS 'nr7',
       CASE WHEN t2.nr_name = 9 THEN t2.nr_val ELSE 0 END AS 'nr9'
FROM table1 AS t1
INNER JOIN  table2 AS t2 ON t1.id = t2.table1id
WHERE t2.name IN (7,9)
GROUP BY t1.id, t1.name
于 2013-04-28T10:56:25.590 回答