我有一個帶有 lane1 和 lane2 映射顏色的事件表,如下所示。
| 事件 | 車道1 | 車道2 |
|---|---|---|
| 79 | 紅色的 | 黃色 |
| 83 | 紅色的 | 白色的 |
| 87 | 藍色的 | 紅色的 |
| 91 | 黃色 | 白色的 |
| 96 | 綠色 | 白色的 |
| 100 | 海軍 | 黃色 |
| 103 | 黃色 | 綠色 |
| 107 | 黃色 | 藍色的 |
| 111 | 黃色 | 海軍 |
| 115 | 藍色的 | 海軍 |
| 119 | 黃色 | 灰色的 |
| 123 | 白色的 | 灰色的 |
所需輸出:
捕獲第一次出現在lane1中的顏色的第n個條目。對于上述輸入,所需的輸出是
| 事件 | 車道1 | nth_entry |
|---|---|---|
| 79 | 紅色的 | 1 |
| 87 | 藍色的 | 1 |
| 91 | 黃色 | 2 |
| 96 | 綠色 | 1 |
| 100 | 海軍 | 1 |
| 123 | 白色的 | 4 |
我嘗試了聚合查詢,例如 lane1, min(event) 但沒有獲得所需的輸出。
select lane1, min(event) from colors group by lane1
uj5u.com熱心網友回復:
join您可以對第一次出現的lane1值執行 self- :
select e1.ev, e1.lane1, sum((e2.lane1 = e1.lane1 or e2.lane2 = e1.lane1)::int)
from (select e.lane1, min(e.event) ev from events e group by e.lane1) e1
join events e2 on e2.event <= e1.ev
group by e1.ev, e1.lane1 order by e1.ev
見小提琴。
uj5u.com熱心網友回復:
利用視窗函式的另一種選擇是:
- 線性化你的資料,
- 計算第 n 個條目
- 為每個 lane1 值提取第一個值
WITH cte AS (
SELECT event_, lane1 AS lane, 1 AS numLane FROM tab
UNION ALL
SELECT event_, lane2 AS lane, 2 AS numLane FROM tab
), ranked AS (
SELECT *, ROW_NUMBER() OVER(PARTITION BY lane ORDER BY event_) AS nth_entry
FROM cte
)
SELECT event_, lane, nth_entry
FROM ranked
WHERE numlane = 1
ORDER BY ROW_NUMBER() OVER(PARTITION BY lane ORDER BY event_)
FETCH FIRST 1 ROWS WITH TIES
在此處查看演示。
uj5u.com熱心網友回復:
lane2我們使用unpivotunion all然后使用row_number()給我們一個顏色第一次出現的lane1時間以及它lane2之前出現的次數。
select event
,color as lane1
,nth_entry
from
(
select *
,row_number() over(partition by color, lane order by event) as rn
,row_number() over(partition by color order by event) as nth_entry
from (
select event, lane1 as color, 'lane1' as lane from t
union all select event, lane2, 'lane2' from t
) t
) t
where lane = 'lane1'
and rn = 1
order by event
| 事件 | 車道1 | nth_entry |
|---|---|---|
| 79 | 紅色的 | 1 |
| 87 | 藍色的 | 1 |
| 91 | 黃色 | 2 |
| 96 | 綠色 | 1 |
| 100 | 海軍 | 1 |
| 123 | 白色的 | 4 |
小提琴
uj5u.com熱心網友回復:
你可以試試:
WITH lane2_color_count as (
SELECT
lane2,
COUNT(1) AS nth_entry
FROM colors
GROUP BY lane2
)
SELECT
min(colors.event) as event,
colors.lane1,
lane2_color_count.nth_entry
FROM
colors
LEFT JOIN lane2_color_count
ON lane2_color_count.lane2 = colors.lane1
GROUP BY colors.lane1, lane2_color_count.nth_entry
ORDER BY event
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/517284.html
下一篇:Django-聚合成陣列
