Select Top row from each group [duplicate] - sql-server

This question already has answers here:
Get top 1 row of each group
(19 answers)
Closed 8 years ago.
I have a table called DynamicText with the following fields: DynamicID, Content, Timestamp, and DynamicTextEnum.
I'm trying to do design a query that would select the most recent record based on Timestamp from each of the groups that are grouped by DynamicTextEnum.
For example:
Enum Timestamp
-----------------
1 1/10/2012
1 2/10/2012
2 1/10/2012
3 3/10/2012
2 3/10/2012
3 4/10/2012
So the results would look like this:
Enum Timestamp
-----------------
1 2/10/2012
2 3/10/2012
3 4/10/2012
My current simply SELECTS TOP 1 them based on Enum and orders them in DESC order based on
Timestamp but it doesn't work when I need all Enums. Any ideas?

;WITH cte AS
(
SELECT *,
ROW_NUMBER() OVER (PARTITION BY DynamicTextEnum ORDER BY Timestamp DESC) AS rn
FROM DynamicText
)
SELECT *
FROM cte
WHERE rn = 1

Take a look at this question and answer:
Efficiently select top row for each category in the set
You can do a sub-query to get the enum/timestamp pair, and join that with your full row. That assumes you don't have duplicate timestamps for any given enum.

Related

Return Only Top Row of SQL Server from duplicated data but different id [duplicate]

This question already has answers here:
Get top 1 row of each group
(19 answers)
Closed 5 months ago.
I have the below table:
ID|NAME|CREATED |TYPE|CARD_NO|
======================================
1 |JOHN|2022-09-21 09:00| 1 |1111111|
2 |JOHN|2022-09-21 09:05| 2 |1111111|
3 |DOE |2022-09-21 09:00| 1 |2222222|
4 |DOE |2022-09-21 09:05| 2 |2222222|
5 |DOE |2022-09-21 09:10| 3 |2222222|
I want to return only the most recent datatime of each row like below:
ID|NAME|CREATED |TYPE|CARD_NO|
======================================
2 |JOHN|2022-09-21 09:05| 2 |1111111|
5 |DOE |2022-09-21 09:10| 3 |2222222|
My query is:
SELECT ID, NAME,MAX(CREATED),TYPE,CARD_NO FROM users group by ID,NAME,TYPE,CARD_NO
However the result is not what I expected, please help me. thank you.
Use ROW_NUMBER coupled with a common table expression or derived table to work out the latest row
;with GetLatestRow
AS(
SELECT RN=row_number()over(partition by t.[name] order by t.Created DESC), --desc to put the lastest row on top
t.*
FROM users t
)
SELECT ID, NAME, CREATED,TYPE,CARD_NO
FROM GetLatestRow
WHERE RN=1

select top 10 records for each group in sql [duplicate]

This question already has answers here:
Select top 10 records for each category
(14 answers)
Closed 8 years ago.
i have table below field
Hour,PathId,Duration,Event,CellId,Channel
Here each cellid have four pathId(i.e, 0,1,2,3),Each pathId have many Events,Channel and Durations.
Now i want to display top 10 records(each pathId) for each cellid.
(group by cellid, pathid and channel we got duration.. we take top ten each pathid based on duration)
i have 50+ cellid and each cellid have four pathid(i.e, 0,1,2,3)
pls help me
!
SampleTable
!
outputtable
i want to display top 10 records(pathId) for each cellid.
You can use the ROW_NUMBER() function to do that, something like:
WITH Ranked
AS
(
SELECT
Hour,PathId,Duration,Event,CellId,Channel,
ROW_NUMBER() OVER(PARTITION BY cellid ORDER BY pathId) AS RN
FROM tablename
)
SELECT Hour,PathId,Duration,Event,CellId,Channel
FROM Ranked
WHERE RN <= 10
The function ROW_NUMBER() OVER(PARTITION BY cellid ORDER BY pathId) will generate a ranking number, by ordering the pathId for each group of cellid and then get the top 10. (Note that this will order by pathId ascending).

SQL Update sequence data based upon date field

I am attempting to update a table that contains deed information. Specifically property ID, sale sequence, and deed date. The program generates the sale sequence data sequentially regardless of the deed date or prior deed information for the property in question.
[property_ID] [sale_number] [sale_deed_date]
1 1 01/15/1990
1 2 06/25/1970
1 3 08/12/1930
What I would like to accomplish is re-sequence sale_number data so they are in chronological order. Similar to this:
[property_ID] [sale_number] [sale_deed_date]
1 1 08/12/1930
1 2 06/25/1970
1 3 01/15/1990
Any help with this would be greatly appreciated.
You can do this by grabbing the correct order in a cte:
;WITH cte AS (SELECT property_ID, sales_number, sales_deed_date, rn = ROW_NUMBER() OVER (PARTITION BY Property_ID ORDER BY sales_deed_date) FROM tablename)
UPDATE t
SET t.sales_number = cte.rn
FROM tablename t
INNER JOIN cte ON t.property_ID = cte.property_ID AND t.sales_deed_date = cte.sales_deed_date

How do I put the results of each group on one row? [duplicate]

This question already has answers here:
SQL group_concat function in SQL Server [duplicate]
(4 answers)
Closed 8 years ago.
select id, productid, optionid
from tableA
where productid = 1
result (id, productid, optionid)
1 1 1
2 1 2
3 1 5
I would like the result to be (productid, optionids):
1 1,2,5
Naturally, I would think the query below should produce the above result
select productid, optionid
from tableA
group by productid
But what function do I put optionid in?
You can use FOR XML PATH (with some help from STUFF function) to do that. You cannot group as there's sadly no aggregate function for concatenating strings.
select distinct a.productid,
stuff((select ','+cast(s.optionid as varchar(10))
from tableA s
where s.productid = a.productid
for XML path('')),1,1,'')
from tableA a
SQL Fiddle demo

T-SQL SELECT DISTINCT & ROW_NUMBER() OVER Ordering Problem

I'm trying to select DISTINCT rows from a view using ROW_NUMBER() OVER for paging. When I switched the ORDER BY field from a SMALLDATETIME to INT I started getting weird results:
SELECT RowId, Title, HitCount FROM
( SELECT DISTINCT Title, HitCount, ROW_NUMBER() OVER(ORDER BY HitCount DESC) AS RowId FROM ou_v_Articles T ) AS Temp
WHERE RowId BETWEEN 1 AND 5
This query returns:
RowId | Title | HitCount
=======================
4 --- 9
1 --- 43
3 --- 11
2 --- 13
5 --- 0
The results are obviously not in the correct order. I'm not sure what the problem is here, but when I removed DISTINCT it orders them correctly.
Thanks.
Applying DISTINCT to a column list containing ROW_NUMBER() will always result in every row being distinct, as there is one ROW_NUMBER per row.
Is the RowId value you're getting correct? Perhaps you just need an ORDER BY RowId clause on the outer query?
Have you tried just using an order by on the outer select and removing the OVER clause?

Resources