合并选择前 1 条 SQL 语句

Combine select top 1 SQL Statements(合并选择前 1 条 SQL 语句)
本文介绍了合并选择前 1 条 SQL 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有 4 个选择语句:

I have 4 select statements:

SELECT top 1 software, auditDate, versionNumber FROM table1 where software = 'software1' order by auditDate desc
SELECT top 1 software, auditDate, versionNumber FROM table1 where software = 'software2' order by auditDate desc
SELECT top 1 software, auditDate, versionNumber FROM table1 where software = 'software3' order by auditDate desc
SELECT top 1 software, auditDate, versionNumber FROM table1 where software = 'software4' order by auditDate desc

目前,每个 select 语句都返回一个包含一行的表,如下所示:

Currently, each select statement returns a table with one row like this:

   software  | auditDate  | versionNumber
1| software1 | 8/22/2017  | 5.0

如果 top 1 条件不存在,那么结果表将有更多行具有不同 auditDateversionNumber,但我只需要每个软件的最新记录 (auditDate).

If the top 1 condition wasn't there, then the result table would have more rows of the same software with different auditDate and versionNumber, but I only needed the most recent record (auditDate) for each software.

我想将所有这些选择语句合并到一个查询中,该查询返回一个类似于以下的表:

I'd like to roll all these select statements into one query that returns a table similar to this:

   software  | auditDate  | versionNumber
1| software1 | 8/22/2017  | 5.0
2| software2 | 8/20/2017  | 5.3
3| software3 | 8/21/2017  | 4.9
4| software4 | 8/16/2017  | 5.6

其中每一行都与上面的单个 select top 1 语句相同.

where each row is the same as the individual select top 1 statement above.

由于 order by 子句,UNION 似乎不起作用,我对其他解决方案感到困惑.

A UNION doesn't seem to work because of the order by clause and I'm stumped for other solutions.

推荐答案

另一个选项是使用 WITH TIES 子句

Another Option is using the WITH TIES clause

Select top 1 with ties 
       software, auditDate, versionNumber 
 From  table1 
 Where software IN ('software1','software2','software3','software4')
 Order By Row_Number() over (Partition By software Order By auditDate Desc)

这篇关于合并选择前 1 条 SQL 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)