如何使用SQL
获取最后一笔付款示例:
SELECT DATEOFPAYMENT
FROM PAYMENTS
WHERE DATEOFPAYMENT = (SELECT MAX(DATEOFPAYMENT) FROM PAYMENTS)
但这不起作用,因为它抱怨要求分组?
答案 0 :(得分:2)
SELECT DATEOFPAYMENT
FROM PAYMENTS
WHERE DATEOFPAYMENT = (SELECT MAX(DATEOFPAYMENT) FROM PAYMENTS GROUP BY DATEOFPAYMENT);
答案 1 :(得分:2)
如果只需要一个字段,为什么还需要子查询?
select max(DateOfPayment)
FROM Payments
如果您想要“上次付款”中的所有数据
select p.Id, p.DateOfPayment, p.Name -- don't know your fields, just an example
FROM Payments p
INNER JOIN (select Id, MAX(DateOfPayment) maxdate
FROM Payments
GROUP BY Id) as m
ON m.Id = p.Id and p.DateOfPayment = m.maxdate
如果您只想要其他字段,并且这些其他字段具有max dateOfPayment,那么不在聚合函数中的所有字段都必须在GROUP BY子句中
select p.Id, p.Name, max(p.DateOfPayment)
From Payments p
GROUP BY p.Id, p.Name
答案 2 :(得分:1)
我通常会使用TOP
和ORDER BY
。
SELECT TOP 1 DATEOFPAYMENT
FROM PAYMENTS
ORDER BY DATEOFPAYMENT DESC
或者获得整个记录:
SELECT TOP 1 *
FROM PAYMENTS
ORDER BY DATEOFPAYMENT DESC
答案 3 :(得分:0)
SELECT TOP 1 DATEOFPAYMENT
FROM PAYMENTS
ORDER BY DATEOFPAYMENT DESC
答案 4 :(得分:0)
gluop使用的所有聚合函数cluase:
选择付款日期 来自付款 DATEOFPAYMENT =(由DATEOFPAYMENT从支付组中选择MAX(DATEOFPAYMENT))
答案 5 :(得分:0)
你有2个选项,选择MAX值
select max(DateOfPayment) FROM Payments
或按DateOfPayment desc
选择前1个DateOfPayment订单运行两者,检查计划和性能并选择最佳的一个:)
答案 6 :(得分:0)
如果你只想要它只是
,那么你要求最后一次付款SELECT MAX(dateofpayment)AS DateOfPAyment FROM Payment
或者,例如,如果您想要一个列出每个员工最后一次付款的清单,您将使用
SELECT MAX(dateofpayment)FROM Payment GROUP BY EmployeeID
您被要求分组的原因是因为您正在使用聚合函数