如何透过此SQL结果?

时间:2011-09-22 01:56:26

标签: sql-server pivot

什么是PIVOT这个SQL结果的最佳方法?我想知道计数(*)是否可以作为枢轴的一部分而不是必须先对数据进行分组?

SELECT 
    e.fullname,
    e.BusinessUnit,  
    COUNT(*) as total  
FROM EmpComplaints e  
WHERE e.BusinessUnit in ('1-Sales', '2-Tech', '3-Marketing')    
GROUP BY e.fullname, e.BusinessUnit
order by e.fullname, e.BusinessUnit

我基本上向每位员工报告他们在三个业务部门中的每一个都有报告的数量:销售,技术,营销。并希望得到一个结果,列出左边的全名,每个名称出现一次,每个名称都有一列('1-Sales','2-Tech','3-Marketing'),其中包含一个数字将是计数(*)

2 个答案:

答案 0 :(得分:1)

这是MS SQL Server吗?这可能有用,抱歉,没有它运行,所以无法验证:

select fullname, 
    sum(case BusinessUnit when '1-Sales' then 1 else 0 end) as Sales,
    sum(case BusinessUnit when '2-Tech' then 1 else 0 end) as Tech,
    sum(case BusinessUnit when '3-Marketing' then 1 else 0 end) as Marketing
FROM EmpComplaints
GROUP BY fullname;

答案 1 :(得分:0)

以下是在SQL Server 2005/2008中执行此操作的方法:

SELECT
    FullName
    ,[1-Sales]
    ,[2-Tech]
    ,[3-Marketing]
     FROM
(
SELECT 
    e.fullname,
    e.BusinessUnit,
    COUNT(*) AS Total  
FROM EmpComplaints e  
WHERE e.BusinessUnit in ('1-Sales', '2-Tech', '3-Marketing')
GROUP BY e.fullname,e.BusinessUnit    
) AS bu
PIVOT
(
SUM(Total)
FOR BusinessUnit IN ([1-Sales], [2-Tech], [3-Marketing])
) AS pvt
ORDER by fullname