【发布时间】:2012-08-26 12:49:21
【问题描述】:
;WITH n AS
(
SELECT problemID, StationName, problemCode, ProblemCreateDate, probCount,
c = COUNT(*) OVER (PARTITION BY StationName, problemCode),
rn = ROW_NUMBER() OVER
(
PARTITION BY StationName, problemCode ORDER BY ProblemCreateDate DESC, problemID DESC
)
FROM dbo.tblProblems
)
SELECT problemID, StationName, problemCode, ProblemCreateDate, c
FROM n WHERE rn = 1;
还有一个名为 tblCustomers 的表,其中有一列 isAssistent Type(bit)
我尝试进行内部连接,但它对我来说太复杂了,并且在尝试使用 inner join 的过滤器时出现错误
tblCustomers where tblCustomers.isAssistent =1
我将非常感激并很高兴知道如何编写正确的语法
重新编辑
inner join tblCustomers on tblProblems.CustID = tblCustomers.custID
错误,我最后一次尝试
Msg 4104, Level 16, State 1, Line 14 多部分标识符 无法绑定“tblProblems.CustID”。消息 4104,级别 16,状态 1, 第 12 行 多部分标识符“tblproblems.problemID”不能 边界。 Msg 4104, Level 16, State 1, Line 12 多部分标识符 无法绑定“tblproblems.custID”。消息 4104,级别 16,状态 1, 第 12 行 多部分标识符“tblproblems.StationName”不能 约束。 Msg 4104, Level 16, State 1, Line 12 多部分 无法绑定标识符“tblproblems.problemCode”。消息 4104, Level 16, State 1, Line 12 多部分标识符 无法绑定“tblproblems.ProblemCreateDate”。
这是我的疯狂猜测:
;WITH n AS
(
SELECT tblCustomers.*,tblproblems.problemID, tblproblems.StationName, tblproblems.problemCode, tblproblems.ProblemCreateDate, tblproblems.probCount,
c = COUNT(*) OVER (PARTITION BY tblproblems.StationName, tblproblems.problemCode),
rn = ROW_NUMBER() OVER
(
PARTITION BY tblproblems.StationName, tblproblems.problemCode ORDER BY tblproblems.ProblemCreateDate DESC, tblproblems.problemID DESC
)
FROM dbo.tblProblems
inner join tblCustomers on tblProblems.CustID = tblCustomers.custID
)
SELECT tblCustomers.*, tblproblems.problemID, tblproblems.custID, tblproblems.StationName, tblproblems.problemCode, tblproblems.ProblemCreateDate, c
FROM n
inner join tblCustomers on tblProblems.CustID = tblCustomers.custID
WHERE rn = 1;
目的是仅在 tblCustomers.isAssistent=1 时才获得 tblProblems 的选择结果
【问题讨论】:
-
你能发布抛出的错误吗?
-
用pk信息转发帖子
-
外部
SELECT引用别名tblProblems,但应该引用n。它也将从tblCustomers返回数据,但不是您期望的方式,因为它在外部SELECT中是JOINed。
标签: sql-server-2008 count inner-join window-functions