SQL 中两个表的输出

Output of two tables in SQL

我正在学习SQL并且遇到了下面提到的场景。

Table 1
id  Name City
1   Ryan Chennai
2   Tom  Banglore
3   Sam  Pune
4   Kat  Mumbai

Table 2
id month salary
1  prev  1000
1  cur   4000
1  next  3000
2  prev  1000
2  cur   3000
2  next  4000
3  prev  2000
3  cur   5000
3  next  6000
4  prev  1500
4  cur   2500
4  next  3000

输出 table 应如下所示

id  name city      cur  prev next
1   Ryan Chennai   4000 1000 3000
2
3
4

(其他id也类似。)

那么实现这一目标的不同方法是什么?如果有人帮助我了解如何解决这类问题,那将非常有帮助。

首先我们创建数据。

DROP TABLE IF EXISTS table_1;
DROP TABLE IF EXISTS table_2;

CREATE TABLE table_1 (
  id INT PRIMARY KEY,
  Name VARCHAR(10),
  City VARCHAR(10)
);

CREATE TABLE table_2 (
    id INT,
    month VARCHAR(10),
    salary INT);

INSERT INTO table_1
VALUES (1, 'Ryan', 'Chennai'),
       (2, 'Tom', 'Banglore'),
       (3, 'Sam', 'Pune'),
       (4, 'Kat', 'Mumbai');

INSERT INTO table_2
VALUES (1, 'prev', 1000),
       (1, 'cur', 4000),
       (1, 'next', 3000),
       (2, 'prev', 1000),
       (2, 'cur', 3000),
       (2, 'next', 4000),
       (3, 'prev', 2000),
       (3, 'cur', 5000),
       (3, 'next', 6000),
       (4, 'prev', 1500),
       (4, 'cur', 2500),
       (4, 'next', 3000);

为了达到预期的结果,我们 join id 列上的 table 和 month 列上的 sum,取仅分别考虑需要的值。

SELECT t1.name
     , t1.city
     , SUM(CASE WHEN t2.month = 'cur' THEN salary ELSE 0 END) AS 'cur'
     , SUM(CASE WHEN t2.month = 'prev' THEN salary ELSE 0 END) AS 'prev'
     , SUM(CASE WHEN t2.month = 'next' THEN salary ELSE 0 END) AS 'next'
  FROM table_1 AS t1
       INNER JOIN table_2 AS t2 
                  USING (id)
 GROUP BY t1.name, t1.city;

我们得到以下table:

name city cur prev next
Ryan Chennai 4000 1000 3000
Tom Banglore 3000 1000 4000
Sam Pune 5000 2000 6000
Kat Mumbai 2500 1500 3000