我正在使用XAMPP MYSQL
我有表,Date
列是字符串
Date | Customer | Location | Cash | Balance |
2015/6/23 LBalance California 5000 3000
2015/6/25 LBalance New York 6000 4500
2015/6/25 InHoss Dept. South Beach 15000 1000
2015/6/20 InHoss Dept. South Beach 15000 1000
2015/6/17 InHoss Dept. South Beach 15000 1000
2015/6/22 LBalance California 5000 4000
2015/6/22 LBalance New York 6000 6000
2015/6/17 InHoss Dept. North Beach 18000 1000
如何选择查询具有不同位置的每个客户的最新日期记录?
期待结果:
Date | Customer | Location | Cash | Balance |
2015/6/23 LBalance California 5000 3000
2015/6/25 LBalance New York 6000 4500
2015/6/25 InHoss Dept. South Beach 15000 1000
2015/6/17 InHoss Dept. North Beach 18000 1000
这是我最接近的:选择客户,位置,现金,余额,最大(日期)AS" As Of"来自mytable WHERE Customer =' LBalance' GROUP BY客户,位置。虽然它显示了客户的最新日期,但另一列只显示了他们的第一个结果。
答案 0 :(得分:0)
从xampp中选择(*) 其中date =(从xampp中选择max(date))
答案 1 :(得分:0)
试试吧
with cte (date, Customer, Location, Cash , Balance) as
(
select cast('2015/6/23' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 3000 Balance
union all
select cast('2015/6/25' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 4500 Balance
union all
select cast('2015/6/25' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/20' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/17' as datetime) date, 'InHoss Dept.' Customer, 'South Beach' Location, 15000 Cash , 1000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'California' Location, 5000 Cash , 4000 Balance
union all
select cast('2015/6/22' as datetime) date, 'LBalance' Customer, 'New York' Location, 6000 Cash , 6000 Balance
union all
select cast('2015/6/27' as datetime) date, 'InHoss Dept.' Customer, 'North Beach' Location, 18000 Cash , 1000 Balance
)
select m.Date, m.Customer, m.Location, m.Cash, m.Balance
from cte m
where m.Date = (select max(mm.Date)
from cte mm
where mm.customer=m.customer
and mm.location = m.location )
我已经检查过我的例子,确实你正在使用mysql示例
答案 2 :(得分:0)
获取最新记录,您使用max()函数,就像您使用group by的每个客户和位置一样 检查一下:
public Button btn2;
public void onClick(){
btn2=(Button)findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,submit.class);
startActivity(intent);
}
});
}
修改。如果日期是varchar(逻辑错误),你可以在下面做。
select max(date) , CUSTOMER, LOCATION from table GROUP BY CUSTOMER , LOCATION
答案 3 :(得分:0)
因为,你想要一个日期到字符串转换。不确定这是否需要,因为,如果没有转换,max(date)可能仍然有用。
select max(STR_TO_DATE(Date, '%Y/%m/%d')),Customer, location, cash,balance from YourTable group by Customer, Location
快乐编码..请确认您的需求。变得难以跟踪编辑。
答案 4 :(得分:0)
也许你可以试试这个
select a.*
from yourtable a JOIN
( select Customer,Location,Max(Date) as Mdate
from yourtable
group by Customer,Location) b
on a.Customer=b.Customer and a.Location=b.Location and a.Date=b.Mdate