我有一個這樣的資料集:
| 用戶身份 | 產品編號 | 分數 |
|---|---|---|
| 一種 | 1 | 4 |
| 一種 | 2 | 4 |
| 一種 | 3 | 5 |
| 乙 | 1 | 4 |
| 乙 | 2 | 4 |
| 乙 | 3 | 5 |
我想要這樣的輸出:
| 用戶 ID1 | 用戶 ID2 | 匹配產品 |
|---|---|---|
| 一種 | 乙 | 1 2 3 |
但我只能通過此查詢獲得前兩列:
CREATE TABLE score_greater_than_3 AS
SELECT userid, productid, score
FROM reviews
WHERE score >= 4;
SELECT s1.userid as userid1, s2.userid as userid2
FROM score_greater_than_3 s1
INNER JOIN score_greater_than_3 s2 ON s1.productid=s2.productid AND s1.userid<s2.userid
GROUP BY s1.userid, s2.userid
HAVING count(*)>=3;
我怎樣才能得到匹配的產品?如果這樣的輸出更容易,我也可以
| 用戶1 | 用戶2 | 配套產品 |
|---|---|---|
| 一種 | b | 1 |
| 一種 | b | 2 |
| 一種 | b | 3 |
uj5u.com熱心網友回復:
您可以嘗試使用以下查詢:
WITH cte AS (
SELECT r.userid,
r.productid
FROM reviews r
WHERE r.score > 3
)
SELECT r1.userid,
r2.userid,
GROUP_CONCAT(r1.productid SEPARATOR ' ')
FROM cte r1
INNER JOIN cte r2
ON r1.productid = r2.productid
AND r1.userid < r2.userid
GROUP BY r1.userid,
r2.userid
HAVING COUNT(*) >= 3
它使用公用表運算式,允許您將表分配到一個持續到查詢結束的臨時空間中。使用自聯接的下一步是正確的,盡管它缺少GROUP_CONCAT聚合函式,該函式允許您在類似字串的欄位上進行聚合。您可以設定“分隔符”引數來決定要使用哪個字串來連接您的值。
在這里嘗試完整的查詢。
uj5u.com熱心網友回復:
請試試這個:
select s1.userid as userid1, s2.userid as userid2,
GROUP_CONCAT(s1.productid)
from score_greater_than_3 s1 inner join score_greater_than_3 s2 on s1.productid=s2.productid and s1.userid<s2.userid
group by s1.userid, s2.userid;
整個腳本請看: DB Fiddle
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/476291.html
上一篇:如何將兩列合并為一列?
下一篇:多對多關系knexjs
