[英]Select rows with max value of a column
I have a table like the following: 我有一个如下表:
acct_id----+---Bill_Id-------+--Bill_dt-----+---alt_bill_id--
12345 123451 02-JAN-2014 101
12345 123452 02-JAN-2014 102
12346 123461 02-JAN-2014 103
12347 123471 02-JAN-2014 104
I need to fetch the data ignoring the least alt_bill_id
if there are two rows for same acct_id
. 如果相同的
acct_id
有两行,则需要忽略最小的alt_bill_id
来获取数据。 In this case I need to ignore the row for acct_id
12345 and alt_bill_id 101. I need a result like the following: 在这种情况下,我需要忽略
acct_id
12345和alt_bill_id 101的行。我需要如下结果:
acct_id----+---Bill_Id-------+--Bill_dt-----+---alt_bill_id--
12345 123452 02-JAN-2014 102
12346 123461 02-JAN-2014 103
12347 123471 02-JAN-2014 104
You have to use a sub-query to find the highest value( bill_id
), then join to that sub-query. 您必须使用子查询来找到最大值(
bill_id
),然后加入该子查询。 Like this: 像这样:
SELECT main.* FROM my_table AS main
JOIN (
SELECT MAX(bill_id) AS bill_id
FROM my_table
GROUP BY acct_id
) AS highest
ON highest.bill_id = main.bill_id;
And here is the SQLFiddle for anyone who wishes to try it out: http://sqlfiddle.com/#!2/fc66a/2 这是任何想要尝试的人的SQLFiddle: http ://sqlfiddle.com/#!2/fc66a/2
I have used the query like this: 我已经使用过这样的查询:
SELECT T1.* FROM CI_BILL T1
WHERE ALT_BILL_ID IN (SELECT MAX(ALT_BILL_ID)
FROM CI_BILL T2 GROUP BY T2.ACCT_ID);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.