我有一個資料庫,其中包含這樣的 pacient 治療日期:
pacient_id | date | type | finish
1 | 2021-01-05 | routine | null
1 | 2021-01-10 | routine | null
1 | 2021-01-22 | routine | null
1 | 2021-01-30 | routine | yes
1 | 2021-02-04 | routine | null
1 | 2021-02-12 | routine | null
1 | 2021-02-19 | routine | null
1 | 2021-02-22 | routine | yes
我需要在查詢中添加一個新列,以顯示咨詢是第一次處理還是第二次處理,例如:
pacient_id | date | type | finish | treatment
1 | 2021-01-05 | routine | null | 1
1 | 2021-01-10 | routine | null | 1
1 | 2021-01-22 | routine | null | 1
1 | 2021-01-30 | routine | yes | 1
1 | 2021-02-04 | routine | null | 2
1 | 2021-02-12 | routine | null | 2
1 | 2021-02-19 | routine | null | 2
1 | 2021-02-22 | routine | yes | 2
當完成列=是時,則處理完成。該表有許多患者:
pacient_id | date | type | finish
1 | 2021-01-05 | routine | null
2 | 2021-01-10 | routine | null
5 | 2021-01-22 | routine | null
2 | 2021-01-30 | routine | yes
1 | 2021-02-04 | routine | null
3 | 2021-02-12 | routine | null
9 | 2021-02-19 | routine | null
1 | 2021-02-22 | routine | yes
所以我訂購了 pacient_id 和日期。感謝幫助。
uj5u.com熱心網友回復:
嘗試這個 :
SELECT pacient_id, date, type, finish
, 1 count(*) FILTER (WHERE finish = 'yes') OVER (PARTITION BY pacient_id ORDER BY date ASC ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS treatment
FROM your_table
在dbfiddle中查看測驗結果
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436576.html
標籤:sql PostgreSQL
下一篇:選擇帶有“case”運算式的變數
