简体   繁体   English

查询以获取具有其中之一的不同值的多列

[英]Query to fetch multiple columns with distinct values for one of these

I have a table with the following columns : id, int_value, date, desc . 我有一个包含以下列的表格:id,int_value,date,desc。 Primary key is (id, int_value, date). 主键是(id,int_value,日期)。

I would like to query the table to get id, int_value and date columns but with distinct id and int_value ordered in desc. 我想查询表以获取id,int_value和date列,但在desc中具有不同的id和int_value。

For example, imagine you have the following rows in the table 例如,假设您在表中有以下几行

id | int_value | date | desc
1       150      2016   desccc
2       120      2014   ddd
1       160      2016   aaa
3       180      2015   ccc
2       135      2016   ddd

With my query, I would like to get that : 与我的查询,我想得到:

id | int_value | date | desc
3       180      2015   ccc
1       160      2016   aaa
2       135      2016   ddd

For the moment, I made the following query : 目前,我进行了以下查询:

select id, int_value, date from table t where int_value = (select
   max(int_value) from table where t.id = id) order by int_value desc;

It works well but if there are same int_value values for a given id, there will be two rows for the same id. 效果很好,但是如果给定的id有相同的int_value值,则同一个ID将有两行。

My question is : can you help me to create a query to avoid this problem ? 我的问题是:您能帮我创建一个查询来避免此问题吗?

Update 更新资料

It seems the following query do the job : 似乎以下查询完成了这项工作:

SELECT id, MAX(int_value) AS score, date FROM table GROUP BY id order by score desc

Thanks for your help. 谢谢你的帮助。

Sylvain 西尔万

One method is to emulate row_number() using variables: 一种方法是使用变量模拟row_number()

select id, int_value, date
from (select id, int_value, date,
             (@rn := if(@i = id, @rn + 1,
                        if@i := id, 1, 1)
                       )
             ) as rn
      from table t cross join
           (select @i := 0, @rn := 0) params
      order by id, int_value desc
     ) t
where rn = 1;
select a.*, b.[desc] from
 (select id, max(int_value) as int_value, max(date) as date from YourTableName group by id) a 
left join  YourTableName b on (a.id=b.id and a.int_value=b.int_value and a.date=b.date)
order by date

this produces the result you want: 这将产生您想要的结果:

id          int_value   date        desc
----------- ----------- ----------- ------
3           180         2015        ccc
1           160         2016        aaa
2           135         2016        ddd

(3 row(s) affected)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM