我有一个表存储ID,用户,排名和CreatedDate。排名可以重复。我想将用户排名第4位,并获取排名1,2,3和4的最新20记录。
表格示例:
ID User Ranking CreatedDate
----------------------------------------
1 B.Sisko 1st 1461136714
2 B.Sisko 2nd 1461123378
3 B.Sisko 3rd 1461123378
4 B.Sisko 3rd 1461600137
5 K.Janeway 3rd 1461600137
6 K.Janeway 4th 1461602181
7 K.Janeway 4th 1461603096
8 J.Picard 3rd 1461603096
9 J.Picard 4th 1461603096
10 J.Picard 4th 1461603096
我想要的结果是:
ID User Ranking CreatedDate
----------------------------------------
1 B.Sisko 1st 1461136714
2 B.Sisko 2nd 1461123378
3 B.Sisko 3rd 1461123378
4 B.Sisko 3rd 1461600137
5 K.Janeway 3rd 1461600137
6 K.Janeway 4th 1461602181
7 J.Picard 3rd 1461603096
8 J.Picard 4th 1461603096
我想要一个能够检索它的查询。任何帮助将不胜感激。
答案 0 :(得分:0)
如果没有某种第三方添加,您不能在SQL Server中使用LIMIT,但行号可能有用。
我不确定日期会发生什么,但这是一个想法:
WITH cte_1 AS(
SELECT MIN(DATE) AS DATE
, USER
, RANK
FROM TABLE
WHERE RANK = 4
GROUP BY USER, RANK
UNION ALL
SELECT DATE
, USER
, RANK
FROM TABLE
WHERE RANK <> 4
),
cte_2 AS (
SELECT *, ROW_NUMBER() OVER(ORDER BY USER, RANK) as run
FROM cte_1
)
SELECT *
FROM cte_2
WHERE rank <= 20
答案 1 :(得分:0)
我想,你想要ORDER BY
USER
和RANK
:
SELECT * FROM TABLE ORDER BY USER,RANK LIMIT 20
答案 2 :(得分:0)
如果Ranking
不等于4 或 Ranking
为4,则以下查询将保留记录,但它最早为CreatedDate
那个排名。
SELECT t1.*
FROM yourTable t1
LEFT JOIN
(
SELECT Ranking, MIN(CreatedDate) AS CreatedDate
FROM yourTable
GROUP BY Ranking
) t2
ON t1.Ranking = t2.Ranking AND t1.CreatedDate = t2.CreatedDate
WHERE t1.Ranking <> '4th' OR (t1.Ranking = '4th' AND t2.Ranking IS NOT NULL)
答案 3 :(得分:0)
尚未确定您的问题,但请尝试关注;)
select *
from table1
where `Ranking` in ('1st', '2nd', '3rd', '4th')
group by
case `Ranking`
when '4th' then concat(`User`, `Ranking`)
else `ID` end
order by id
答案 4 :(得分:0)
下面的代码可能很有用
;WITH CTE AS
(
SELECT ROW_NUMBER()OVER(PARTITION BY [USER],RANKING ORDER BY Ranking,CreatedDate) as RN, * FROM #T
)
,CTE1 AS (
SELECT * from CTE WHERE Ranking IN ('1st','2nd','3rd')
)
SELECT ROW_NUMBER()OVER(ORDER BY ID) AS ID,[User]
, Ranking
,CreatedDate
FROM(
SELECT ID,[User]
, Ranking
,CreatedDate
FROM CTE1
UNION ALL
SELECT ID,[User]
, Ranking
,CreatedDate
FROM CTE
WHERE RN =1 AND Ranking NOT IN ('1st','2nd','3rd')
) T