我有以下表格 -
Resource
--------------------
Id, ProjectId, Hours, ApproverId
Project
--------------------
Id, Name
输入是ApproverId。我需要检索所有匹配ApproverId的行(足够简单)。对于我得到的每一个资源,我还需要获得他们的批准时间(相同的表),其中approverId不是传入的资源(业务需求,在UI中变灰)。我现在正在做的是 - 获取基于ApproverId的所有资源,将它们存储在临时表中,然后在Resource.Id上执行不同的操作,将其存储在不同的临时表中,然后对于每个Resource.Id,获取ApproverId 不是传递的行。我可以在一个查询中组合它而不是使用临时表吗?
谢谢!
编辑:我正在使用SQL Server 2008 R2。
编辑2:这是我的存储过程。阅读完评论后,我略微改变了逻辑。我们可以摆脱所有临时表并使其更快 -
ALTER PROCEDURE GetResourceDataByApprover
@ApproverId UNIQUEIDENTIFIER
AS
CREATE TABLE #Table1
(
Id SMALLINT PRIMARY KEY
IDENTITY(1, 1) ,
ResourceId UNIQUEIDENTIFIER
)
CREATE TABLE #Table2
(
ResourceId UNIQUEIDENTIFIER ,
ProjectId UNIQUEIDENTIFIER ,
ProjectName NVARCHAR(1024)
)
INSERT INTO #Table1
SELECT DISTINCT
ResourceId
FROM dbo.Resource T
WHERE T.ApproverId = @ApproverId
DECLARE @i INT
DECLARE @numrows INT
DECLARE @resourceId UNIQUEIDENTIFIER
SET @i = 1
SET @numrows = ( SELECT COUNT(*)
FROM #Table1
)
IF @numrows > 0
WHILE ( @i <= ( SELECT MAX(Id)
FROM #Table1
) )
BEGIN
SET @resourceId = ( SELECT ResourceId
FROM #Table1
WHERE Id = @i
)
INSERT INTO #Table2
SELECT
T.ResourceId ,
T.ProjectId ,
P.Name AS ProjectName
FROM dbo.[Resource] T
INNER JOIN dbo.Project P ON T.ProjectId = P.ProjectId
WHERE T.ResourceId = @resourceId
SET @i = @i + 1
END
SELECT *
FROM #Table1
SELECT *
FROM #Table2
DROP TABLE #Table1
DROP TABLE #Table2
答案 0 :(得分:1)
此查询应为每个资源返回两行,一行用于指定的批准者,另一行用于所有其他批准者。
SELECT
Id,
CASE
WHEN ApproverId=@approverId THEN 'SpecifiedApprover'
ELSE 'OtherApprover'
END AS Approver,
SUM(Hours) AS Hours
FROM Resource
GROUP BY
Id,
CASE
WHEN ApproverId=@approverId THEN 'SpecifiedApprover'
ELSE 'OtherApprover'
END
答案 1 :(得分:0)
你想知道具体的审批人如何浪费他的时间吗?
SELECT p.Id, p.Name, SUM(r.Hours) as TotalHours
FROM Resource r
LEFT JOIN Project p
ON r.ProjectId = p.Id
WHERE ApproverId = %ConcreteApproverId%
GROUP BY p.Id, p.Name
HAVING SUM(r.Hours) > 0
此查询将生成此表示例:
+-----+----------+-------+
| Id | Project | Hours |
+-----+----------+-------+
| 203 | ProjectA | 25 |
| 202 | ProjectB | 34 |
| 200 | ProjectC | 46 |
+-----+----------+-------+