爲了使數據合理(即沒有重複記錄),我必須稍微改變模式。
CREATE TABLE book_condition (
created TIMESTAMP,
book_id INTEGER,
condition VARCHAR,
PRIMARY KEY (created, book_id));
INSERT INTO book_condition (created, book_id, condition)
VALUES
('2016-01-01 08:30', 1, 'Taken'),
('2016-01-01 08:35', 1, ''),
('2016-01-01 08:40', 1, 'Taken'),
('2016-01-01 08:45', 1, ''),
('2016-01-01 08:50', 2, 'Taken'),
('2016-01-01 08:55', 3, 'Taken'),
('2016-01-01 09:00', 3, ''),
('2016-01-01 09:05', 3, 'Taken'),
('2016-01-01 09:10', 3, 'Taken'),
('2016-01-01 09:15', 4, ''),
('2016-01-01 09:20', 4, 'Taken');
CREATE TABLE book (
book_id INTEGER,
name VARCHAR,
PRIMARY KEY (book_id));
INSERT INTO book (book_id, name)
VALUES
(1, 'BookA'),
(2, 'BookB'),
(3, 'BookC'),
(4, 'BookD');
然後,問題分解成:
SELECT
book_id,
COUNT(book_id) AS total_taken
FROM book_condition
WHERE
condition = 'Taken'
GROUP BY book_id
;
book_id | total_taken
---------+-------------
1 | 2
2 | 1
3 | 3
4 | 1
(4 rows)
SELECT
book_id,
total_taken,
RANK() OVER (
ORDER BY total_taken DESC
) AS total_taken_rank
FROM (
SELECT
book_id,
COUNT(book_id) AS total_taken
FROM book_condition
WHERE
condition = 'Taken'
GROUP BY book_id
) AS bt
ORDER BY total_taken_rank ASC
;
book_id | total_taken | total_taken_rank
---------+-------------+------------------
3 | 3 | 1
1 | 2 | 2
2 | 1 | 3
4 | 1 | 3
(4 rows)
- 如何獲得這本書的名字包含其鍵(
id
)值的查詢結果呢?
SELECT
b.book_id,
b.name,
bt.total_taken,
RANK() OVER (
ORDER BY bt.total_taken DESC
) AS total_taken_rank
FROM
book AS b
LEFT JOIN (
SELECT
book_id,
COUNT(book_id) AS total_taken
FROM book_condition
WHERE
condition = 'Taken'
GROUP BY book_id
) AS bt
USING (book_id)
ORDER BY
total_taken_rank ASC,
book_id ASC
;
book_id | name | total_taken | total_taken_rank
---------+-------+-------------+------------------
3 | BookC | 3 | 1
1 | BookA | 2 | 2
2 | BookB | 1 | 3
4 | BookD | 1 | 3
(4 rows)
SELECT
br.book_id,
br.name,
br.total_taken
FROM (
SELECT
b.book_id,
b.name,
bt.total_taken,
RANK() OVER (
ORDER BY bt.total_taken DESC
) AS total_taken_rank
FROM
book AS b
LEFT JOIN (
SELECT
book_id,
COUNT(book_id) AS total_taken
FROM book_condition
WHERE
condition = 'Taken'
GROUP BY book_id
) AS bt
USING (book_id)
) AS br
WHERE
total_taken_rank = 1
;
book_id | name | total_taken
---------+-------+-------------
3 | BookC | 3
(1 row)
數據使沒有道理;這意味着有多個記錄完全相同?請發佈一個[最小,完整,可驗證的示例](https://stackoverflow.com/help/mcve)我們可以運行的SQL代碼,以獲取與您相同的架構和數據。 – bignose
@bignose「ID」號碼是本書的ID。每個都有多個副本,這就是ID號在第一個表中重複多次的原因。 – Anstane