我很难将这两个SQL查询结合起来。我有这个原始查询从两个表中选择数据,相关列是Tasks.CustomerID和Customers.CustomerID。它基本上是任务。* + Customers.Name
ALTER PROCEDURE [dbo].[SP_SelectTasksandName]
AS
SELECT TASKS.CustomerID, TASKS.DateCreation, TASKS.DateFinish, TASKS.Description, TASKS.Fees, TASKS.Hours, TASKS.InvoiceNum, TASKS.PaymentMethod,
TASKS.Status, TASKS.TaskID, CUSTOMERS.Name
FROM TASKS, CUSTOMERS
WHERE (TASKS.CustomerID LIKE CUSTOMERS.CustomerID)
这样可行,但我现在已被要求将此查询限制为指定的行数。我发现这个代码适用于我的其他更简单的查询,但我似乎无法正确使用此查询。此限制代码如下。 (即所有行> @low&& rows< = @high)
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY CustomerID) as row FROM CUSTOMERS
) a WHERE ((a.row > @low and a.row <= @high)
这是我最接近的,但我被困在这里。
SELECT * FROM (
SELECT *, ROW_NUMBER() OVER (ORDER BY TASKS.CustomerID) as row FROM
(SELECT TASKS.CustomerID, TASKS.DateCreation, TASKS.DateFinish, TASKS.Description, TASKS.Fees, TASKS.Hours, TASKS.InvoiceNum, TASKS.PaymentMethod,
TASKS.Status, TASKS.TaskID, CUSTOMERS.Name
FROM TASKS, CUSTOMERS
WHERE (TASKS.CustomerID LIKE CUSTOMERS.CustomerID))
) a WHERE (a.row > @low and a.row <= @high)
在最后一行的第一个括号上出现“期望为id或引用ID”的错误。
对于noob问题感到抱歉,感谢你们给予的任何帮助。
答案 0 :(得分:1)
从不在hello world
子句中使用逗号。 始终使用正确的FROM
语法。
您要查找的查询可以写为:
JOIN
答案 1 :(得分:0)
我会按如下方式编写查询:
;With CTE
As
(
SELECT
TASKS.CustomerID,
TASKS.DateCreation,
TASKS.DateFinish,
TASKS.Description,
TASKS.Fees,
TASKS.Hours,
TASKS.InvoiceNum,
TASKS.PaymentMethod,
TASKS.Status,
TASKS.TaskID,
CUSTOMERS.Name,
Row_Number() over (Partition By Tasks.CustomerID Order by Tasks.CustomerID) as RN
FROM TASKS
Inner Join CUSTOMERS
on (TASKS.CustomerID = CUSTOMERS.CustomerID)
)
select * -- just being lazy here - in production code you ALWAYS use an explicit field list
from CTE
Where CTE.RN > @low and CTE.RN <= @high -- or whatever logic you need