簡體   English   中英

如何選擇符合條件的第一行

[英]How to select the first row that met condition

我在PostgreSQL中具有以下視圖:

idshipment idorder  quantity_order  date   quantity_in_shipment percent_sent
 50          1        1020         1.1.16    432                    42
 51          1        1020         17.1.16   299                    71
 51          1        1020         20.1.16   144                    85
 51          1        1020         45.1.16   145                    100
 52          2         1           3.1.17    5                      100

此視圖顯示每個訂單的出貨量。 例如:

idorder = 1由4批次發送:

首批發貨的數量是432,這意味着已發送訂單的42%

第二次發貨的數量是299,這意味着訂單的71%已發送

第三次發貨的數量是144,這意味着已發送訂單的85%

第四批發貨的數量是145,這表示已發送100%的訂單

我需要一個查詢,該查詢將向我顯示每個訂單發送到75%以上的第一個日期 表示每個訂單僅顯示一行。 對於以上數據,我應該看到:

idorder date
1       20.1.16  (cause its 85% first time above 75%)
2       3.1.17   (cause its 100% first time above 75%)

我怎樣才能做到這一點?

您可以使用distinct on

select distinct on (t.idshipment) t.*
from t
where t.percent_sent >= 75
order by t.idshipment, t.percent_sent asc;

嘗試這樣的事情:

SELECT iorder, MIN("date") AS "date"
  FROM your_view
  WHERE percent_sent >= 75
  GROUP BY iorder

使用group by ,讓每一個記錄idorderMIN()來聚集date選擇的最早日期

我創建了一個包含您提供的數據的表調用裝運:並執行此查詢

SELECT s.idorder, MIN(s.date) as date
FROM shipment s
WHERE percent_sent >= 75
GROUP BY s.idorder

結果:

idorder     date
----------- ----------
1           2016-01-20
2           2017-03-01

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM