MSSQL从一个数据集创建多个列

时间:2015-01-06 14:12:14

标签: sql sql-server

到目前为止,我已经构建了这个SQL查询。它按预期工作但不完整。

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 [PSU Card]
FROM  OPERATION
INNER JOIN REQUIREMENT ON REQUIREMENT.WORKORDER_BASE_ID = OPERATION.WORKORDER_BASE_ID
    AND REQUIREMENT.WORKORDER_SUB_ID = OPERATION.WORKORDER_SUB_ID
    AND REQUIREMENT.WORKORDER_LOT_ID = OPERATION.WORKORDER_LOT_ID
WHERE OPERATION.[STATUS] ='R' 
    AND OPERATION.RESOURCE_ID LIKE '%{Root Container.equipmentName}%'
    AND REQUIREMENT.PART_ID LIKE '%PSU%'

棘手的部分是REQUIREMENT.PART_ID实际上有4列信息。例如。当前表中的最后一列拉出包含“PSU”的值。另一个相邻列将从包含“PCH”的同一列中提取数据我不知道处理这个问题的最佳方法是什么。 UNION声明是最好的方式还是可以通过CASE声明完成的事情?

:: EDIT ::

根据新信息,我尝试了数据透视表和案例陈述。我不太清楚如果没有条件语句,数据透视表将如何适用于此应用程序。似乎CASE语句可行。从这里汲取灵感,SQL Server: Examples of PIVOTing String data,我试过了。

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]
    ,MAX(
        CASE WHEN REQUIREMENT.PART_ID LIKE '%PSU%' 
        THEN REQUIREMENT.PART_ID ELSE '' END 
    ) AS [PSU Card]
    ,MAX(
        CASE WHEN REQUIREMENT.PART_ID LIKE '%PCH%' 
        THEN REQUIREMENT.PART_ID ELSE '' END 
    ) AS [DIE #]      
FROM  OPERATION
INNER JOIN REQUIREMENT ON REQUIREMENT.WORKORDER_BASE_ID = OPERATION.WORKORDER_BASE_ID
    AND REQUIREMENT.WORKORDER_SUB_ID = OPERATION.WORKORDER_SUB_ID
    AND REQUIREMENT.WORKORDER_LOT_ID = OPERATION.WORKORDER_LOT_ID
WHERE OPERATION.[STATUS] ='R' 
    AND OPERATION.RESOURCE_ID LIKE '%{Root Container.equipmentName}%'
    AND REQUIREMENT.PART_ID LIKE '%PSU%'

我得到的错误信息是:

database=FV_VM)@5000ms
On: FV_Recipe_Page.Root Container.Table.data
caused by GatewayException: Column 'OPERATION.WORKORDER_BASE_ID' 
is invalid in the select list because it is not contained in 
either an aggregate function or the GROUP BY clause.
caused by SQLServerException: Column 'OPERATION.WORKORDER_BASE_ID'
is invalid in the select list because it is not contained in either
an aggregate function or the GROUP BY clause.

要温柔。我知道我的语法错了,这就是为什么我在问问题。我是SQL的新手,从未成功使用过PIVOT或CASE语句。

0 个答案:

没有答案