table1&表2:
table1 & table2 http://aftabfarda.parsfile.com/1.png
SELECT *
FROM (SELECT DISTINCT dbo.tb1.ID, dbo.tb1.name, ROW_NUMBER() OVER (ORDER BY tb1.id DESC) AS row
FROM dbo.tb1 INNER JOIN
dbo.tb2 ON dbo.tb1.ID = dbo.tb2.id_tb1) AS a
WHERE row BETWEEN 1 AND 7
ORDER BY id DESC
结果:
Result... http://aftabfarda.parsfile.com/3.png
(id 11重复3次)
我如何获得此输出:
ID name row
-- ------ ---
11 user11 1
10 user10 2
9 user9 3
8 user8 4
7 user7 5
6 user6 6
5 user5 7
答案 0 :(得分:3)
您可以使用子查询在distinct
之前应用row_number
:
select *
from (
select row_number() over (order by tbl.id desc) as row
, *
from (
select distinct t1.ID
, tb1.name
from dbo.tb1 as t1
join dbo.tb2 as t2
on t1.ID = t2.id_tb1
) as sub_dist
) as sub_with_rn
where row between 1 and 7
答案 1 :(得分:0)
除@Andomar's suggestion之外,您可以使用DENSE_RANK
代替ROW_NUMBER
并先排序(在子查询中),然后应用{{1} (在外部查询中):
DISTINCT
类似但不完全相同,虽然两者可能归结为相同的查询计划,但我不确定。我认为值得测试。
当然,你也可以尝试半 -join而不是SELECT DISTINCT
ID,
name,
row
FROM (
SELECT
t1.ID,
t1.name,
DENSE_RANK() OVER (ORDER BY t1.ID DESC) AS row
FROM dbo.tb1 t1
INNER JOIN dbo.tb2 t2 ON t1.ID = t2.id_tb1
) AS a
WHERE row BETWEEN 1 AND 7
ORDER BY ID DESC
或IN
形式的正确联接,以防止重复第一名:
EXISTS