如何合并两个表,并保留它们共享的列,同时添加不共享的其他列?

时间:2019-12-12 05:23:14

标签: mysql

说我有两个表:

+--------+-----+ 
| bookID | Jan | 
+--------+-----+ 
| 1094   | 1   | 
| 1058   | 1   | 
| 984    |  1  | 
+--------+-----+ 
+--------+-----+ 
| bookID | Dec | 
+--------+-----+ 
| 1      | 1   | 
| 2      | 1   | 
+--------+-----+

我想得到:

+--------+-----+-----+ 
| bookID | Jan | Dec |
+--------+-----+-----+ 
| 1094   | 1   | 0   | 
| 1058   | 1   | 0   | 
| 984    | 1   | 0   | 
| 1      | 0   | 1   | 
| 2      | 0   | 1   | 
+--------+-----+-----+

我当时想在id上使用join并使用union来获取两个表中都没有的bookID,但这似乎效率不高,因为在接下来的几个月中我将不得不这样做。

是否可以从此表中找到更好的方法:

+----+--------+-----------+--------------+------------+------------+----------+ 
| id | bookID | studentID | checkOutDate | returnDate |  dueDate   | extended | 
+----+--------+-----------+--------------+------------+------------+----------+ 
| 1  | 25     | 1         | 2019-12-09   |  NULL      | 2019-12-25 | 0        | 
| 2  | 357    | 2         | 2019-12-09   | NULL       | 2019-12-25 | 0        | 
| 3  | 365    | 3         | 2019-12-09   | NULL       | 2019-12-25 | 0        | 
| 4  | 984    | 8         | 2019-12-09   | NULL       | 2019-12-25 | 0        |
| 5  | 1094   | 1         | 2019-12-09   | NULL       | 2019-12-25 | 0        | 
| 11 | 99     | 2         | 2019-01-11   | NULL       | 2019-12-10 | 0        | 
| 12 | 1      | 2         | 2019-01-24   | NULL       | 2019-01-11 | 0        | 
+----+--------+-----------+--------------+------------+------------+----------+

我想显示一本书的列表,每本书13列:12列显示每月的结帐次数,第13列显示该书的年度结帐。

1 个答案:

答案 0 :(得分:0)

使用CASE从原始表中获取每个月的计数作为列,使用GROUP BY来获取按书和年份的行是相当直接的(但是有点冗长)。

SELECT 
  bookID, YEAR(checkoutDate) `year`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  1 THEN 1 END) `jan`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  2 THEN 1 END) `feb`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  3 THEN 1 END) `mar`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  4 THEN 1 END) `apr`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  5 THEN 1 END) `may`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  6 THEN 1 END) `jun`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  7 THEN 1 END) `jul`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  8 THEN 1 END) `aug`,
  COUNT(CASE WHEN MONTH(checkoutDate) =  9 THEN 1 END) `sep`,
  COUNT(CASE WHEN MONTH(checkoutDate) = 10 THEN 1 END) `oct`,
  COUNT(CASE WHEN MONTH(checkoutDate) = 11 THEN 1 END) `nov`,
  COUNT(CASE WHEN MONTH(checkoutDate) = 12 THEN 1 END) `dec`,
  COUNT(*) `year total checkouts`
FROM myTable
GROUP BY bookID, YEAR(checkoutDate)

An SQLfiddle to test with