查询1表输出相同的列两次,不同的过滤器显示另一个不是

时间:2013-09-05 20:16:19

标签: sql sql-server sql-server-2008

我正在尝试两次使用不同的过滤器查看同一列。使用SQL Server 08

例如:在我正在调用DPO的列中,我只想显示作业代码abc和xyz。标记为“需要工作”的列需要显示除作业代码abc和xyz之外的所有代码。

以下是我的查询的一部分减去一些表来缩短它,这就是我从3个表中提取的原因。

SELECT 

WkRoDesc.Job_Code AS [Work Needed], 
WkRoDesc.Job_Code AS [DPO]

FROM vhstock, WkInvReg, WkRoDesc

WHERE vhstock.no = WkInvReg.Stock_No AND WkInvReg.Ro_Number = WkRoDesc.Ro_Number

1 个答案:

答案 0 :(得分:0)

这样的东西?或者你想用行做更多的事情?

编辑:已针对SQL Server兼容性进行了修改:

SELECT
  CASE WHEN WkRoDesc.Job_Code = 'abc' 
         OR WkRoDesc.Job_Code = 'xyz'
    THEN NULL ELSE WkRoDesc.Job_Code END AS WorkNeeded,
  CASE WHEN WkRoDesc.Job_Code = 'abc' 
         OR WkRoDesc.Job_Code = 'xyz'
    THEN WkRoDesc.Job_Code ELSE NULL END AS DPO
FROM vhstock, WkInvReg, WkRoDesc
WHERE vhstock.no = WkInvReg.Stock_No
  AND WkInvReg.Ro_Number = WkRoDesc.Ro_Number

注意:这几乎听起来像你正在寻找一个GROUP_CONCAT(),但我想我等着确定......

EDIT2:这在SQL Server中使用一些丑陋的XML处理来执行类似MySQL GROUP_CONCAT的操作。

SELECT
  stuff((
    select cast(',' as varchar(max)) + j.Job_Code
    from WkRoDesc AS j
    where j.Ro_Number = WkInvReg.Ro_Number
      and NOT (j.Job_Code = 'abc' OR j.Job_Code = 'xyz')
    order by j.Job_Code
    for xml path('')
    ), 1, 1, '') AS WorkNeeded,    
  stuff((
    select cast(',' as varchar(max)) + j.Job_Code
    from WkRoDesc AS j
    where j.Ro_Number = WkInvReg.Ro_Number
      and (j.Job_Code = 'abc' OR j.Job_Code = 'xyz')
    order by j.Job_Code
    for xml path('')
    ), 1, 1, '') AS DPO
FROM vhstock, WkInvReg, WkRoDesc
WHERE vhstock.no = WkInvReg.Stock_No
  AND WkInvReg.Ro_Number = WkRoDesc.Ro_Number
GROUP BY WkInvReg.Ro_Number

这是希望它适用于您的系统!