如何根据最旧的日期对值进行 GROUP 和 return?
How to GROUP and return a value based on the oldest date?
所以我有这个 table:
n | id_product | name | price | quantity | created_at
-------------------------------------------------------------------------------
1 1da05150 pencil 800 10 31-12-2021
2 1da05150 pencil 700 7 15-01-2022
3 1da05150 pencil 1500 13 20-01-2022
4 510eac00 book 350 25 29-12-2021
我想按 ID_PRODUCT 列对它们进行分组。
在 return 上我想要的列是 ID_PRODUCT、NAME、id_product 的数量总和,对于 PRICE 列,我想获得来自的价格值最旧的产品(出于价格目的,我希望它考虑 CREATED_AT 列)
结果应该是这样的:
n | id_product | name | price | quantity | created_at
-------------------------------------------------------------------------------
1 1da05150 pencil 800 30 31-12-2021
2 510eac00 book 350 25 29-12-2021
你需要 Subquery
才能加入 table 自身
你的数据
create temporary table tmp_a (
n int
,id_product VARCHAR(30)
,name VARCHAR(30)
,price int
,quantity int
,created_at date
);
INSERT INTO tmp_a
(n,id_product,name,price,quantity,created_at)
VALUES (1,'1da05150','pencil',800,10,'12-31-2021'),
(2,'1da05150','pencil',700,7,'01-15-2022'),
(3,'1da05150','pencil',1500,13,'01-20-2022'),
(4,'510eac00','book',350,25,'12-29-2021');
您的查询
SELECT t1.n,
t1.id_product,
t1.NAME,
t1.price,
t2.quantity,
t2.created_at
FROM tmp_a t1
JOIN (SELECT id_product,
NAME,
Sum(quantity) quantity,
Min(created_at) created_at
FROM tmp_a
GROUP BY id_product,
NAME) t2
ON t1.id_product = t2.id_product
AND t1.created_at = t2.created_at
所以我有这个 table:
n | id_product | name | price | quantity | created_at
-------------------------------------------------------------------------------
1 1da05150 pencil 800 10 31-12-2021
2 1da05150 pencil 700 7 15-01-2022
3 1da05150 pencil 1500 13 20-01-2022
4 510eac00 book 350 25 29-12-2021
我想按 ID_PRODUCT 列对它们进行分组。 在 return 上我想要的列是 ID_PRODUCT、NAME、id_product 的数量总和,对于 PRICE 列,我想获得来自的价格值最旧的产品(出于价格目的,我希望它考虑 CREATED_AT 列)
结果应该是这样的:
n | id_product | name | price | quantity | created_at
-------------------------------------------------------------------------------
1 1da05150 pencil 800 30 31-12-2021
2 510eac00 book 350 25 29-12-2021
你需要 Subquery
才能加入 table 自身
你的数据
create temporary table tmp_a (
n int
,id_product VARCHAR(30)
,name VARCHAR(30)
,price int
,quantity int
,created_at date
);
INSERT INTO tmp_a
(n,id_product,name,price,quantity,created_at)
VALUES (1,'1da05150','pencil',800,10,'12-31-2021'),
(2,'1da05150','pencil',700,7,'01-15-2022'),
(3,'1da05150','pencil',1500,13,'01-20-2022'),
(4,'510eac00','book',350,25,'12-29-2021');
您的查询
SELECT t1.n,
t1.id_product,
t1.NAME,
t1.price,
t2.quantity,
t2.created_at
FROM tmp_a t1
JOIN (SELECT id_product,
NAME,
Sum(quantity) quantity,
Min(created_at) created_at
FROM tmp_a
GROUP BY id_product,
NAME) t2
ON t1.id_product = t2.id_product
AND t1.created_at = t2.created_at