sql查询冲突

时间:2015-02-26 19:53:22

标签: mysql sql

我需要一个返回group wise max(cus_amount)的查询,然后应该选择date作为修改日期的最后日期。

select cus_name , sum(cus_amount),first(cus_date)
from  credit_details
group by cus_name

问题是日期选择不正确,如果我有5个数据,它选择第一个,要求是我最近更新的最后数据。请帮忙 我的表值

ID  cus_id  cus_date    cus_name    cus_amount  cus_details
7   1   16/04/2014  NAGARAJAN   256 aaa
8   1   11/04/2014  NAGARAJAN   25  aaa
9   1   11/04/2014  NAGARAJAN   22  aaa 
10  4   11/04/2014  SPS 55  bbb
11  102 14/04/2014  PRK 100 25
12  102 16/04/2014  PRK 100 25

我的要求是:

Nagaraj  303 16/04/2014
sps      55  11/04/2014
prk      200 16/04/2014

2 个答案:

答案 0 :(得分:1)

您可以使用MAX()函数获取组中的最新日期:

SELECT cus_name, SUM(cus_amount) AS totalCustomerAmount, MAX(cus_date) AS latestDate
FROM credit_details
GROUP BY cus_names;

答案 1 :(得分:1)

SELECT cus_name, 
       SUM(cus_amount) AS totalCustomerAmount, 
       MAX(STR_TO_DATE(cus_date, '%d/%m/%Y')) AS latestDate
FROM credit_details
GROUP BY cus_names;

对于mssql尝试这种方式:

SELECT cus_name, 
       SUM(cus_amount) AS totalCustomerAmount, 
       MAX(CONVERT(date,cus_date,103)) AS latestDate
FROM credit_details
GROUP BY cus_names;

for ms access试试这个:

SELECT cus_name, 
       SUM(cus_amount) AS totalCustomerAmount, 
       MAX(CDate(cus_date)) AS latestDate
FROM credit_details
GROUP BY cus_names;