我有一个DB表,其中包含Payment(商家,交易,TimeStamp)。对于教学交易,我们可以有多个商家。现在我想形成一个查询,其中对于(val1,val2,val3)中的事务,我们将得到做最新事务的商家.eg:
Merchant Transaction Time
----------------------------------
M1 T1 t1
M2 T1 t2
M1 T1 t3
M3 T2 t4
M4 T2 t5
M5 T3 t6
所以如果在(T1,T2.T3)中的transactionid,我们将得到M1(因为M1在时间t3上做了最新的T1交易),M4,M5 (t1<t2 timestamp)
答案 0 :(得分:1)
select * from Payment
group by transaction
order by Time desc;
答案 1 :(得分:1)
试试这个:
SELECT p.Merchant
FROM Payment p
JOIN
(SELECT Merchant, Transaction, MAX(Time) as time
FROM Payment GROUP BY Merchant, Transaction) t
ON (p.Merchant = t.Merchant AND p.Transaction = t.Transaction AND p.Time = t.time)
答案 2 :(得分:1)
SELECT Merchant FROM DB_TABLE WHERE transaction IN(T1, T2, T3) ORDER
BY Time DESC LIMIT 1
答案 3 :(得分:1)
您可以使用Last()函数在分割所有横切后获取最后一行。
答案 4 :(得分:1)
您要查找的SQL语句如下:
SELECT p.Merchant, p.Transaction, p.Time
FROM Payment p
JOIN
(SELECT Transaction, MAX(Time) as time
FROM Payment
WHERE Transaction IN('T1', 'T2', 'T3')
GROUP BY Transaction) t
ON (p.Transaction = t.Transaction AND p.Time = t.time)
根据您的示例查看此SQLFiddle以获取结果。