我有一个非常复杂的查询,它连接了八 (8) 个不同的表。
不过,为了这个问题,我将使用这种类型的结构对其进行简化:
create table table1(PacketID int, RequestID int, EmpID int, PartNo varchar(20))
insert into table1 values
(1 , 1, 132, 'abc123'),
(1 , 2, 132, 'abc456'),
(1 , 3, 132, 'def123'),
(1 , 4, 132, 'def456'),
(2 , 5, 228, 'xyz123'),
(3 , 6, 239, 'xyz321'),
(3 , 7, 239, 'aaa000')
这种类型的表会创建以下输出:
|_P_|_R_|_Emp_|_PartNo_|
|_1_|_1_|_132_|_abc123_|
|_1_|_2_|_132_|_abc465_|
|_1_|_3_|_132_|_def123_|
|_1_|_4_|_132_|_def456_|
|_2_|_5_|_228_|_xyz123_|
|_3_|_6_|_239_|_xyz321_|
|_3_|_7_|_239_|_aaa000_|
我在这里整理了一个小提琴:http ://www.sqlfiddle.com/#!3/a3ce4/1
我被告知他们并不真正需要这个PacketID
or RequestID
,但他们需要的是显示一个数据包中有多少请求以及该数据包的请求编号需要注意的东西。
我仍然需要PacketID
andRequestID
值来更改数据。
所以,我想在上表中添加一列,如下所示:
|_P_|_R_|_ReadAs_|_Emp_|_PartNo_|
|_1_|_1_|_1 of 4_|_132_|_abc123_|
|_1_|_2_|_2 of 4_|_132_|_abc465_|
|_1_|_3_|_3 of 4_|_132_|_def123_|
|_1_|_4_|_4 of 4_|_132_|_def456_|
|_2_|_5_|_1 of 1_|_228_|_xyz123_|
|_3_|_6_|_1 of 2_|_239_|_xyz321_|
|_3_|_7_|_2 of 2_|_239_|_aaa000_|
我该怎么做呢?
如果你只是想感受我的痛苦并查看我的 SQL Server 上定义的完整视图,这里是:
SELECT P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID,
EI.FIRSTNAME + ' ' + EI.LASTNAME AS Employee, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo,
R.Workorder, R.Qty, RZ.Description AS ReasonType, R.MTF,
A.StatusID, S.Description AS Status, A.EmpID AS Stator,
A.DateStamp AS Stated
FROM dbo.Packet AS P
LEFT OUTER JOIN dbo.Request AS R ON R.PacketID = P.ID
INNER JOIN dbo.Action AS A ON R.ID = A.RequestID
LEFT OUTER JOIN dbo.Action AS A2 ON A.RequestID = A2.RequestID
AND (A.DateStamp < A2.DateStamp OR
A.DateStamp = A2.DateStamp AND A.RequestID < A2.RequestID)
INNER JOIN CPAPP.AIO_Test_Results.dbo.EmployeeInfo AS EI ON A.EmpID = EI.COUNT
INNER JOIN dbo.RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN dbo.Line AS L ON R.LineID = L.ID
INNER JOIN dbo.ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN dbo.Status AS S ON A.StatusID = S.ID
WHERE (A2.RequestID IS NULL)