[英]How to get the latest available-stock value from the following data in postgresql for the respective itemname?
Refer to the following sample data.请参阅以下示例数据。
|availablestock | itemname | tdate |
|----------------|------------|-------------------|
|86 |ABC |2020-01-29 19:44:43|
|90 |ABC |2020-01-27 19:32:59|
|88 |ABC |2020-01-29 19:46:35|
|100 |Soap |2020-01-26 19:46:35|
|98 |Soap |2020-02-29 19:46:35|
The following result needed-需要以下结果-
|availablestock | itemname | tdate |
|----------------|------------|-------------------|
|88 |ABC |2020-01-29 19:46:35|
|98 |Soap |2020-02-29 19:46:35|
Do you need below -你需要下面 -
SELECT max(availablestock)
FROM YOUR_TABLE
WHERE tdate BETWEEN '2020-01-20' AND '2020-01-29'
I think you are looking for order by
and limit
我认为您正在寻找
order by
和limit
SELECT availablestock FROM TABLE
WHERE TDATE BETWEEN '2020-01-20' AND '2020-01-29'
ORDER BY TDATE DESC LIMIT 1
Test Script测试脚本
DROP TABLE IF EXISTS "Items";
CREATE TABLE IF NOT EXISTS "Items"
(
"Id" SERIAL NOT NULL PRIMARY KEY,
"Name" VARCHAR(64) NOT NULL,
"Stock" INT NOT NULL,
"TDate" TIMESTAMP NOT NULL
);
INSERT INTO "Items"("Name", "Stock", "TDate") VALUES ('ABC', 86, '2020-01-29 19:44:43');
INSERT INTO "Items"("Name", "Stock", "TDate") VALUES ('ABC', 90, '2020-01-27 19:32:59');
INSERT INTO "Items"("Name", "Stock", "TDate") VALUES ('ABC', 88, '2020-01-29 19:46:35');
SELECT * FROM "Items"
WHERE "TDate" <@ tsrange('[2020-01-20 00:00:00 , 2020-01-30)')
--//Included lowerbound and excluded upper bound -- Valid values 2020-01-20 00:00:00 to 2020-01-29 23:59:59
ORDER BY "TDate" DESC
LIMIT 1
In the text form of a range, an inclusive lower bound is represented by "[" while an exclusive lower bound is represented by "(". Likewise, an inclusive upper bound is represented by "]", while an exclusive upper bound is represented by ")"在文本形式的范围中,包含下限用“[”表示,不包含下限用“(”表示。同理,包含上限用“]”表示,不包含上限用“(”表示经过 ”)”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.