[英]Extract row data from query given a date and a common value in sql
我有下表:
CREATE TABLE my_table
(
the_id varchar(6) NOT NULL,
the_amount int NOT NULL,
the_date date NOT NULL
)
INSERT INTO my_table
VALUES ('LMUS01', '200', '2/12/2019'),
('LMUS01', '200', '2/11/2019'),
('LMUS01', '300', '2/13/2019'),
('LMUS02', '100', '2/10/2019'),
('LMUS02', '150', '2/12/2019')
而我要的是LMUS01的第一天的金额。 当我尝试:
SELECT the_amount, MIN(the_date)
FROM my_table
WHERE the_id = 'LMUS01'
它告诉我the_amount
必须出现在GROUP BY
子句中。 但组必须是the_id
,我试过:
SELECT the_amount, MIN(the_date)
FROM my_table
WHERE the_id = 'LMUS01'
GROUP BY the_id
结果必须是:
200, 2/11/2019
任何帮助将不胜感激。
我会在这里使用LIMIT
:
SELECT *
FROM my_table
WHERE the_id = 'LMUS01'
ORDER BY the_date
LIMIT 1;
要获取每个 ID 的最早记录,请使用DISTINCT ON
:
SELECT DISTINCT ON (the_id) *
FROM my_table
ORDER BY the_id, the_date;
如果你真的想让你的原始方法与MIN
函数一起工作,你可以使用子查询:
SELECT *
FROM my_table
WHERE
the_id = 'LMUS01' AND
the_date = (SELECT MIN(the_date) FROM my_table WHERE the_id = 'LMUS01');
但是,我会首先使用其他方法之一,它应该在 Postgres 中表现更好。
这是您可以使用min
函数执行的一种选择:
SELECT the_amount, the_date
FROM my_table
WHERE the_id = 'LMUS1' --<< I have changed this because of varchar(5)
and the_date = (select min(the_date)
from my_table
WHERE the_id = 'LMUS1' ); --<< I have changed this because of varchar(5)
你必须明白这会起作用:
select min(the_date)
from my_table
WHERE the_id = 'LMUS1';
这不会:
select the_amount, min(the_date)
from my_table
WHERE the_id = 'LMUS1';
因为如果它不是聚合函数的一部分,您必须将 select 子句中的每一列放在 group by 子句中。 所以如果你这样写,第二个例子会起作用:
select the_amount, min(the_date)
from my_table
WHERE the_id = 'LMUS1'
group by the_amount;
但是,当然这不会给你想要的结果...... 这是一个演示,你可以在其中看到这个例子的实际效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.