1

使用一个数据库,其中每个订单都有一个分配给它的项目,每个项目都必须有一个开始操作,然后才能发生工作操作,一旦完成,就会执行完成操作。

同一个项目可以有多个开始和结束,但工作只能在开始和结束动作之间进行。

我编写了一个脚本来尝试查找在完成后执行工作但没有开始但它没有返回我想要的值的任何情况。

SELECT
O.ORDER_NUMBER
--,*
FROM
[CUSTOMER] [C]
JOIN
[SITE] [S] ON C.CUSTOMER_ID=S.CUSTOMER_ID
JOIN
[ORDER] [O] ON S.SITE_ID=O.SITE_ID
JOIN
[ITEM] [I] ON O.ORDER_ID=I.ORDER_ID
JOIN
(SELECT
    MAX(ACTION_ID) AS [START_ID]
    ,A2.ITEM_ID
FROM
    [ACTION] [A2]
JOIN
    [ALLOWED_ACTION] [AA2] ON A2.ALLOWED_ACTION_ID = AA2.ALLOWED_ACTION_ID
WHERE
    AA2.DESCRIPTION='START'
GROUP BY
    A2.ITEM_ID) AS [D] ON I.ITEM_ID=D.ITEM_ID
JOIN
(SELECT
    MAX(ACTION_ID) AS [FINISH_ID]
    ,A3.ITEM_ID
FROM
    [ACTION] [A3]
JOIN
    [ALLOWED_ACTION] [AA3] ON A3.ALLOWED_ACTION_ID = AA3.ALLOWED_ACTION_ID
WHERE
    AA3.DESCRIPTION='FINISH'
GROUP BY
    A3.ITEM_ID) AS [F] ON I.ITEM_ID=F.ITEM_ID
JOIN
(SELECT
    MAX(ACTION_ID) AS [LAST_ID]
    ,A4.ITEM_ID
FROM
    [ACTION] [A4]
GROUP BY
    A4.ITEM_ID) AS [L] ON I.ITEM_ID=L.ITEM_ID
WHERE
(L.LAST_ID>F.FINISH_ID)
AND 
(F.FINISH_ID>D.START_ID)

我已经查看了如何从需要在单个查询中首先在 sql server 中添加的表中获得第二高?和其他人喜欢尝试找出答案,但我看不出我做错了什么。

一个典型的结果会给我一个订单号,当我检查动作时,最后一个动作总是一个完成或它有一个开始。

任何帮助对我来说都意义重大。

4

1 回答 1

0

设法找到解决此问题的方法。

我将所有信息放入一个临时表中,然后在临时表上执行最后的条件语句,它调用了我想要的信息。

不确定原始条件语句是否仅在脚本的一部分上起作用,但它必须让比我更聪明的人才能弄清楚:)

无论如何,这是对我有用的最终脚本。

SELECT
O.ORDER_NUMBER
,LAST_ID
,FINISH_ID
,LAST_ID
INTO #TEMP1
--,*
FROM [CUSTOMER] [C]
JOIN [SITE] [S] ON C.CUSTOMER_ID=S.CUSTOMER_ID
JOIN [ORDER] [O] ON S.SITE_ID=O.SITE_ID
JOIN [ITEM] [I] ON O.ORDER_ID=I.ORDER_ID
JOIN (SELECT
    MAX(ACTION_ID) AS [START_ID], A2.ITEM_ID
    FROM [ACTION] [A2]
    JOIN [ALLOWED_ACTION] [AA2] ON A2.ALLOWED_ACTION_ID = AA2.ALLOWED_ACTION_ID
    WHERE AA2.DESCRIPTION='START'
    GROUP BY A2.ITEM_ID) AS [D] ON I.ITEM_ID=D.ITEM_ID
JOIN (SELECT
    MAX(ACTION_ID) AS [FINISH_ID], A3.ITEM_ID
    FROM [ACTION] [A3]
    JOIN [ALLOWED_ACTION] [AA3] ON A3.ALLOWED_ACTION_ID = AA3.ALLOWED_ACTION_ID
    WHERE AA3.DESCRIPTION='FINISH'
    GROUP BY A3.ITEM_ID) AS [F] ON I.ITEM_ID=F.ITEM_ID
JOIN (SELECT
    MAX(ACTION_ID) AS [LAST_ID], A4.ITEM_ID
    FROM [ACTION] [A4]
    GROUP BY A4.ITEM_ID) AS [L] ON I.ITEM_ID=L.ITEM_ID

SELECT ORDER_NUMBER FROM #TEMP1
WHERE LAST_ID>FINISH_ID
AND 
FINISH_ID>START_ID
于 2013-10-09T13:21:57.720 回答