Mysql 按多个列分组
我有一张如下所示的桌子-Mysql 按多个列分组,mysql,group-by,Mysql,Group By,我有一张如下所示的桌子- Id Reference DateAttribute1 DateAttribute2 1 MMM005 2011-09-11 2012-09-10 2 MMM005 2012-06-13 2012-09-10 3 MMM006 2012-08-22 2012-09-10 4 MMM006
Id Reference DateAttribute1 DateAttribute2
1 MMM005 2011-09-11 2012-09-10
2 MMM005 2012-06-13 2012-09-10
3 MMM006 2012-08-22 2012-09-10
4 MMM006 2012-08-22 2012-09-11
我有id值的句柄。我想进行查询,以便得到以下结果
Id Reference DateAttribute1 DateAttribute2
2 MMM005 2012-06-13 2012-09-10
4 MMM006 2012-08-22 2012-09-11
我希望我的结果按引用分组,然后按“DateAttribute1”分组,然后按“DateAttribute2”分组,正如您在结果中看到的那样,DateAttribute1优先于DateAttribute2。 我应该如何编写查询以上述方式获取结果 有什么解决办法吗?试试这个:
select max(id),Reference, min(DateAttribute1),max(DateAttribute2)
group by Reference
select *
from your_table t
join (
select Reference,
min(DateAttribute1) as DateAttribute1,
max(DateAttribute2) as DateAttribute2
from your_table
group by Reference
)a
on t.Reference=a.Reference
and t.DateAttribute1=a.DateAttribute1
and t.DateAttribute2=a.DateAttribute2
从您的_表中选择*按Id描述为x组
参照
假设表名为“tbl2”
select * from (select * from tbl2 order by REFERENCE,DateAttribute1 desc,
DateAttribute2 desc ) as abc group by reference
我不认为这会产生我想要的结果。这里我们假设maxid,我不能在实际场景中假设它。我错过了什么吗。基本上我想查询,这样它会返回正确的id行。在某个时间范围内有多行。如何获得一个id,它将代表该时间范围内的所有行?你不可能需要重新定义你的问题,也许DateAttribute1的优先级高于DateAttribute2,请你解释一下?基本上,在上述情况下,如果有两个参考文献具有相同的参考编号,然后,syem应该查看dateattribute1以查看哪个日期更大,如果它们相同,则应该查看dateattribute2以检查哪个日期更大,然后最终返回相应的行。检查我的查询。。这将一直有效,直到无法使用上述代码获得正确的结果。。非常感谢你的回复……我是不是错过了什么?
select * from (select * from tbl2 order by REFERENCE,DateAttribute1 desc,
DateAttribute2 desc ) as abc group by reference