SQL Server相关查询

时间:2015-01-05 21:43:13

标签: sql sql-server correlated-subquery

我目前有一些看起来像这样的SQL代码。

SELECT
    WORKORDER_BASE_ID As 'Work Order',
    SCHED_START_DATE AS 'Scheduled Start',
    SETUP_HRS AS 'Approx Setup Hrs',
    RUN_HRS AS 'Approx Run Hrs',
    (
        SELECT 
            PART_ID as "Components" 
        FROM 
            REQUIREMENT 
        WHERE 
            REQUIREMENT.WORKORDER_BASE_ID = OPERATION.WORKORDER_BASE_ID
            AND REQUIREMENT.WORKORDER_SUB_ID = OPERATION.WORKORDER_SUB_ID
            AND PART_ID LIKE '%PSU%'
    )   AS PSU
FROM 
    OPERATION
WHERE 
    OPERATION.STATUS = 'R' 
    AND RESOURCE_ID LIKE '%{Root Container.equipmentName}%'

我收到错误,因为子查询会生成多个字段。我需要的是一种为子查询指定条件的方法,只显示与该行中特定工单有关的数据,特别是工单号。我猜这是某种循环功能。

有什么建议吗?

顺便说一下,底线是正确的。我使用的平台将大括号中的值解释为局部变量。

1 个答案:

答案 0 :(得分:1)

select中的子查询必须返回标量值。在您的选择中使用TOP 1,它应该解决问题。或者,您也可以执行以下操作....

SELECT OPERATION.WORKORDER_BASE_ID   AS [Work Order]
      ,OPERATION.SCHED_START_DATE    AS [Scheduled Start]
      ,OPERATION.SETUP_HRS           AS [Approx Setup Hrs]
      ,OPERATION.RUN_HRS             AS [Approx Run Hrs]
      ,REQUIREMENT.PART_ID           AS [Components] 
FROM  OPERATION
INNER JOIN REQUIREMENT ON REQUIREMENT.WORKORDER_BASE_ID = OPERATION.WORKORDER_BASE_ID
                      AND REQUIREMENT.WORKORDER_SUB_ID = OPERATION.WORKORDER_SUB_ID
WHERE OPERATION.[STATUS] ='R' 
  AND OPERATION.RESOURCE_ID LIKE '%{Root Container.equipmentName}%'
  AND REQUIREMENT.PART_ID LIKE '%PSU%'