好的,我有相当大的查询要执行,但我的要求很简单。我需要在我在查询本身中创建的内联表上运行带有 Where 子句的选择查询。
这是代码
SELECT *FROM (
SELECT * FROM
(
SELECT MomentId, Moment, ExpressionsCount, ShareComments, SharedDt, SharedBy, SharedByProfilePicture, OwnerProfilePicture, SharedVia,
MomentOwnerName, SharedById, OwnerId, SharedViaId, ROW_NUMBER() OVER (ORDER BY SharedDt DESC) As RowNum FROM
(
SELECT moments.MomentId,
Moment,
ExpressionsCount =
(SELECT COUNT(ExpressionId) FROM moments_Expressions WHERE moments_Expressions.momentId = moments.momentId),
MomentDt As SharedDt,
'' As ShareComments,
FirstName + ' ' + LastName As SharedBy,
'' As SharedByProfilePicture,
OwnerProfilePicture =
CASE
WHEN ProfilePicture = ''
THEN dbo.fn_GetProfilePicture(1)
ELSE
dbo.fn_GetProfilePicture(0) + ProfilePicture
END,
'' As SharedById,
moments.UserId As OwnerId,
'' As SharedViaId,
'' As SharedVia,
'' As MomentOwnerName,
dbo.fn_CheckUserMomentPrivacy(moments.UserId, @UserId, moments.MomentId) As SharingStatus
FROM moments_Master moments
INNER JOIN tbl_User_Profiles profiles ON profiles.UserId = moments.UserId
WHERE moments.UserId = @FriendId
UNION ALL
SELECT moments.MomentId,
Moment,
ExpressionsCount =
(SELECT COUNT(ExpressionId) FROM moments_Expressions WHERE moments_Expressions.momentId = moments.momentId),
SharedDt,
sharing.ShareComments,
FirstName + ' ' + LastName As SharedBy,
SharedByProfilePicture =
CASE
WHEN ProfilePicture = ''
THEN dbo.fn_GetProfilePicture(1)
ELSE
dbo.fn_GetProfilePicture(0) + ProfilePicture
END,
OwnerProfilePicture =
(
SELECT
CASE
WHEN ProfilePicture = ''
THEN dbo.fn_GetProfilePicture(1)
ELSE
dbo.fn_GetProfilePicture(0) + ProfilePicture
END
FROM tbl_User_Profiles WHERE UserId = moments.UserId
),
CAST(sharing.SharedBy As VARCHAR(40)) As SharedById,
moments.UserId As OwnerId, CAST(sharing.SharedVia As VARCHAR(40)) As SharedViaId,
(SELECT FirstName + ' ' + LastName FROM tbl_User_Profiles WHERE UserId = SharedVia) As SharedVia,
(SELECT FirstName + ' ' + LastName FROM tbl_User_Profiles WHERE UserId = moments.UserId) As MomentOwnerName,
dbo.fn_CheckUserMomentPrivacy(SharedBy, @UserId, moments.MomentId) As SharingStatus
FROM moments_Master moments
INNER JOIN moments_Sharing sharing ON sharing.MomentId = moments.MomentId
INNER JOIN tbl_User_Profiles profiles ON profiles.UserId = sharing.SharedBy
WHERE sharing.SharedBy = @FriendId
--AND dbo.fn_CheckUserMomentPrivacy(SharedBy, @UserId, moments.MomentId) = 1 AND sharing.SharedBy = @FriendId
) Moments
WHERE SharingStatus = 1
) FinalRes
WHERE RowNum BETWEEN @StartRow AND @EndRow
--ORDER BY SharedDt DESC
) UltRes
WHERE RowNum BETWEEN (SELECT RowNum FROM UltRes Where MomentId = 31928) AND CASE WHEN RowNum <=5 THEN (RowNum + 5) ELSE (RowNum - 5)
END
当我运行此查询时,它告诉我 Object is 'UltRes' 无效。我需要 RowNum 介于 MomentId 的 RowNum 之间,并根据其值确定其另一端。
基本上我需要Select
在Where clause
.