使用数据库,其中每个订单都有一个分配给它的项目,并且每个项目都必须在可以发生工作操作之前有一个开始操作,并且一旦完成,就会执行完成操作。
同一个项目可以有多个“开始”和“结束”,但“工作”只能在“开始”和“结束”操作之间执行。
我编写了一个脚本来尝试查找在完成后执行的任何工作但没有启动的情况,但它不会返回我想要的值。
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)
我已经看过How to get the 2nd highest from a table where it need to be added first in sql server in a single query?和其他类似的人试图弄明白,但我看不出我做错了什么。
典型的结果会给我一个订单号,当我检查操作时,最后一个操作总是一个完成,或者它有一个开始。
任何帮助都对我意义重大。
答案 0 :(得分: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