我有这个问题:
SELECT
Reservation.*,
ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL)) AS RowNums
FROM
Reservation
WHERE
RowNums = 1
我收到此错误:
Msg 207,Level 16,State 1,Line 2
列名称无效' RowNums'。
我不知道问题出在哪里 - 有什么帮助吗?
答案 0 :(得分:2)
您无法直接使用RowNums,
试试这个,
SELECT *
FROM
(
SELECT Reservation.*,ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL)) AS RowNums
FROM Reservation
) S
where RowNums = 1
答案 1 :(得分:2)
您需要使用CTE:
WITH tempData AS
(
SELECT Reservation.*,
ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL)) AS RowNums
FROM Reservation
)
SELECT * FROM tempData WHERE RowNums = 1
但是,更简洁的方法是使用WITH TIES
:
SELECT TOP 1 WITH TIES *
FROM Reservation
ORDER BY ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL))
答案 2 :(得分:1)
SELECT t.*
FROM
(SELECT Reservation.*,ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY NULL ) AS RowNums
FROM Reservation) t
where RowNums = 1
答案 3 :(得分:0)
您不能直接使用它,因为这不是表中的列。使用CTE或派生表。
CTE
:WITH C AS (
SELECT Reservation.*,ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL)) AS RowNums
)
SELECT * FROM C WHERE RowNums = 1
答案 4 :(得分:0)
试试这个
;WITH CTE AS(
SELECT Reservation.*,
ROW_NUMBER() OVER (PARTITION BY code_bien ORDER BY (SELECT NULL)) AS RowNums
FROM Reservation)
SELECT * FROM CTE
WHERE RowNums = 1