[英]Select Top 1 based on distinct columns
I need to select the top 1
record from each group of column UnitID
and CompanyCode
and using order by from column CreatedDate
我需要从每组
UnitID
和CompanyCode
列中选择top 1
记录,并使用CreatedDate
列中的 order by
Here's an example of my table这是我的桌子的一个例子
ID | UnitID | CompanyCode | CreatedDate |
----------------------------------------|
1 | A1 | G100 | 2020-03-12 |
2 | A1 | G100 | 2020-03-13 |
3 | A1 | G100 | 2020-03-14 |
4 | B2 | G100 | 2020-03-12 |
5 | B2 | F200 | 2020-03-13 |
6 | B2 | E300 | 2020-03-14 |
My expected results would be these rows我的预期结果将是这些行
ID | UnitID | CompanyCode | CreatedDate |
----------------------------------------|
3 | A1 | G100 | 2020-03-14 |
4 | B2 | G100 | 2020-03-12 |
5 | B2 | F200 | 2020-03-13 |
6 | B2 | E300 | 2020-03-14 |
We looking at UnitID first, next check CompanyCode If there is a record with different CompanyCode
it will be display, but if have same, it will be select top 1 with order by createdDate我们首先查看UnitID,然后检查CompanyCode 如果有不同
CompanyCode
的记录将显示,但如果相同,将按createdDate顺序选择top 1
SIMPLE QUERY: SELECT ID, UnitID, CompanyCode, CreatedDate FROM Tbl_Unit ORDER BY CreatedDate
简单查询:
SELECT ID, UnitID, CompanyCode, CreatedDate FROM Tbl_Unit ORDER BY CreatedDate
Anyone know how this can be achieved?有谁知道这是如何实现的?
If I understand correctly, the next statement may help:如果我理解正确,下一个陈述可能会有所帮助:
SELECT ID, UnitID, CompanyCode, CreatedDate
FROM (
SELECT
ID, UnitID, CompanyCode, CreatedDate,
ROW_NUMBER() OVER (PARTITION BY UnitID, CompanyCode ORDER BY CreatedDate) AS Rn
FROM Tbl_Unit
) t
WHERE Rn = 1
I like using TOP 1 WITH TIES
for handling this type of query on SQL Server:我喜欢在 SQL Server 上使用
TOP 1 WITH TIES
来处理此类查询:
SELECT TOP 1 WITH TIES *
FROM Tbl_Unit
ORDER BY
ROW_NUMBER() OVER (PARTITION BY UnitID, CompanyCode ORDER BY CreatedDate DESC);
Using ROW_NUMBER()
Function.使用
ROW_NUMBER()
函数。
SELECT ID , UnitID , CompanyCode , CreatedDate FROM
(
select TAB.* , ROW_NUMBER() OVER (PARTITION BY UnitId , CompanyCode order by createddate desc ) RNK from TAB
) Drived WHERE RNK=1;
ROW_NUMBER() -- Funtion to generate row number
OVER (PARTITION BY UnitId , CompanyCode -- Partition range
order by createddate desc -- Sorting order )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.