【问题标题】:How do I pivot this SQL result?如何旋转这个 SQL 结果?
【发布时间】:2011-09-22 01:56:25
【问题描述】:

PIVOT 这个 SQL 结果的最佳方法是什么?我想知道 count(*) 是否可以作为数据透视的一部分完成,而不必事先对数据进行分组?

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') 列,其中包含一个数字将是计数(*)

【问题讨论】:

标签: sql-server pivot


【解决方案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;

【讨论】:

    【解决方案2】:

    以下是在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多