Combine select top 1 SQL Statements

筅森魡賤 提交于 2019-12-11 03:43:01

问题


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

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

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

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

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

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


回答1:


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)



回答2:


You can use ROW_NUMBER:

WITH CTE AS
(
    SELECT  *,
            RN = ROW_NUMBER() OVER(PARTITION BY software ORDER BY auditDate DESC)
    FROM dbo.table1
    WHERE software IN ('software1','software2','software3','software4')
)
SELECT *
FROM CTE
WHERE RN = 1;



回答3:


Assuming you have an id col and don't want to name the software use something like:

Select * from ( (Select id, software, max(auditDate) from table1 group by id, software) a Left join table1 b on a.id = b.id)



来源:https://stackoverflow.com/questions/45821615/combine-select-top-1-sql-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!