如何将具有相同信息的数据合并或连接到下一行的一行。
SQL:
SELECT C.[LocationCode]
,C.[PartNumber]
,C.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), C.[BatchQuantity]) AS 'MAC_Outstanding'
FROM CUSTOMER_MN C
WHERE C.[LocationCode] = 'P1'
SELECT R.[LocationCode]
,R.[PartNumber]
,R.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), R.[PlannedQuantity] - R.[ActualQuantity]) AS 'ASY_Outstanding'
FROM CUSTOMER_RH R
WHERE R.[LocationCode] = 'P1'
答案 0 :(得分:2)
为什么不使用join
?
SELECT C.[LocationCode]
,C.[PartNumber]
,C.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), C.[BatchQuantity]) AS 'MAC_Outstanding'
,CONVERT(DECIMAL(18,0), R.[PlannedQuantity] - R.[ActualQuantity]) AS 'ASY_Outstanding'
FROM CUSTOMER_MN C
JOIN CUSTOMER_RH R ON C.LocationCode = R.LocationCode AND C.Partnumber = R.Partnumber AND C.WorksOrderNumber = R.WorksOrderNumber
WHERE C.[LocationCode] = 'P1'
答案 1 :(得分:0)
要合并数据,请使用UNION ALL
:
SELECT C.[LocationCode]
,C.[PartNumber]
,C.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), C.[BatchQuantity]) AS 'MAC_Outstanding'
FROM CUSTOMER_MN C
WHERE C.[LocationCode] = 'P1'
UNION ALL
SELECT R.[LocationCode]
,R.[PartNumber]
,R.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), R.[PlannedQuantity] - R.[ActualQuantity]) AS 'ASY_Outstanding'
FROM CUSTOMER_RH R
WHERE R.[LocationCode] = 'P1'
为了合并数据,请使用以下查询:
Select *
From (
SELECT C.[LocationCode]
,C.[PartNumber]
,C.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), C.[BatchQuantity]) AS 'MAC_Outstanding'
FROM CUSTOMER_MN C
WHERE C.[LocationCode] = 'P1')z1
Left Join (
SELECT R.[LocationCode]
,R.[PartNumber]
,R.[WorksOrderNumber]
,CONVERT(DECIMAL(18,0), R.[PlannedQuantity] - R.[ActualQuantity]) AS 'ASY_Outstanding'
FROM CUSTOMER_RH R
WHERE R.[LocationCode] = 'P1'
)z2 On Z1.LocationCode = Z2.LocationCode, Z1.PartNumber = Z2.PartNumber and Z1.WorkOrderNumber = z2.WorkOrderNumber