T-SQL | SQL-Server Pivot

时间:2015-09-10 06:36:34

标签: sql sql-server tsql

这是当前的查询:

SELECT 
    cod.COM_DESC
   ,count(emp.OBE_Name) colValue
   ,'Total'[Desc] 
FROM OBP_EMP_MASTER emp
LEFT JOIN COMMONCODES cod 
  ON  emp.OBE_AGENT_DR = cod.COM_SLNO 
WHERE OBE_AGENT_DR IS NOT NULL 
GROUP BY cod.COM_DESC

UNION ALL

SELECT 
     cod1.COM_DESC
    ,count(rep.OBE_Name) colValue
    ,'Replaced'[Desc]  
FROM OBP_EMP_REPLACE_HISTORY rep 
LEFT JOIN COMMONCODES cod1 
  ON rep.OBE_AGENT_DR = cod1.COM_SLNO 
WHERE OBE_AGENT_DR IS NOT NULL
GROUP BY cod1.COM_DESC

RESULT

enter image description here

期望的结果

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试:

select
    Agent,
    max(case when `desc` = 'Total' then ColValue else 0 end) Total,
    max(case when `desc` = 'Replaced' then ColValue else 0 end) Replaced
from tbl
group by Agent  

演示 sqlfiddle