我有一张这样的表:
SKU AVG_COST DATE TIME
--------------------------------------------
AAA 1.50 20110301 110331
AAA 1.52 20110302 140005
AAA 1.54 20110303 150301
AAA 1.56 20110303 150302
AAA 1.56 20110303 150303
BBB 2.04 20110408 160258
BBB 2.05 20110409 140808
BBB 2.06 20110410 130509
BBB 2.07 20110411 152331
BBB 2.08 20110411 152332
预期结果应该使用SQL:
SKU AVG_COST DATE TIME
---------------------------------------
AAA 1.56 20110303 150303
BBB 2.08 20110411 152332
我正在尝试提取最新的SKU行。
答案 0 :(得分:4)
SELECT *
FROM tableName
WHERE (sku, date) IN
(
SELECT sku, MAX(date)
FROM tableName
GROUP BY sku
);
考虑到时间:
SELECT *
FROM tableName
WHERE (sku, date, time) IN
(
SELECT sku, date, MAX(time)
FROM tableName
WHERE (sku, date) IN
(
SELECT sku, MAX(date)
FROM tableName
GROUP BY sku
)
GROUP BY sku, date
);
正如OMG Poines所指出的,这种方法仅适用于支持where子句中的元组的数据库。
<强>更新强>
这是一种没有元组的方法:
SELECT *
FROM tableName t
WHERE t.date = (SELECT MAX(date) FROM tableName WHERE sku = t.sku)
AND t.time = (SELECT MAX(time) FROM tableName WHERE sku = t.sku AND date = t.date);
在我的本地postgres服务器上进行的快速测试显示这种方法较慢,但是我设置为测试的表没有索引,所以YMMV。
答案 1 :(得分:0)
我很确定这会为你做到:
SELECT SKU, AVG_COST, MAX(DATE), MAX(TIME)
FROM TABLE
Group BY SKU, AVG_COST
答案 2 :(得分:-2)
查询看起来像这样
select *
from table
group by sku
having max(AVG_COST)
order time desc