Sql Crosstab月份行作为列?

时间:2012-07-19 09:19:13

标签: mysql

早上好,我尝试使用mysql / php创建报告失败,我希望将行作为类似于Access Crosstab或Excel Pivot的列。我有销售人员和我希望在整个页面上显示的月销售额,以月份作为列标题。

我的查询下面会输出数据,但每个销售人员每个月都有一行不能很好地阅读,

      Jan | Feb | Mar | April

的销售额1
Sales2
Sales3
SALES4

Select
  tblcontacts.ContactFullName,
  Count(tblcases.CaseID) As cases,
  MonthName(tblcases.CaseDate) As Monthly
From
  tblcases Inner Join
  tblcontacts On tblcases.ContactAssignedTo =
  tblcontacts.ContactID
Group By
  tblcontacts.ContactFullName,
  MonthName(tblcases.CaseDate)  
  with rollup

蚂蚁的建议或指示赞赏,我已经研究过,但大部分都在我的头上!

亲切的问候

2 个答案:

答案 0 :(得分:1)

Select 
    tblcontacts.ContactFullName, 
    sum(case when MonthName(tblcases.CaseDate)='January' then 1 else 0 end) as January,
    sum(case when MonthName(tblcases.CaseDate)='February' then 1 else 0 end) as February,
    .
    .
    sum(case when MonthName(tblcases.CaseDate)='December' then 1 else 0 end) as December,
From 
  tblcases Inner Join 
  tblcontacts On tblcases.ContactAssignedTo = 
  tblcontacts.ContactID 
  Group By 
  tblcontacts.ContactFullName

答案 1 :(得分:1)

您可以做的只是按每个联系人分组,并使用条件聚合根据每个月计算行数:

SELECT
    a.ContactFullName,
    SUM(MONTH(b.CaseDate) = 1) AS Jan,
    SUM(MONTH(b.CaseDate) = 2) AS Feb,
    SUM(MONTH(b.CaseDate) = 3) AS Mar,
    SUM(MONTH(b.CaseDate) = 4) AS Apr,
    SUM(MONTH(b.CaseDate) = 5) AS May,
    SUM(MONTH(b.CaseDate) = 6) AS Jun,
    SUM(MONTH(b.CaseDate) = 7) AS Jul,
    SUM(MONTH(b.CaseDate) = 8) AS Aug,
    SUM(MONTH(b.CaseDate) = 9) AS Sep,
    SUM(MONTH(b.CaseDate) = 10) AS Oct,
    SUM(MONTH(b.CaseDate) = 11) AS Nov,
    SUM(MONTH(b.CaseDate) = 12) AS Dec
FROM
    tblcontacts a
INNER JOIN
    tblcases b ON a.ContactID = b.ContactAssignedTo
GROUP BY
    a.ContactFullName

修改:根据您对此答案的评论:要获得每月的价格总和,您可以执行以下操作:

SELECT
    a.ContactFullName,
    SUM(IF(MONTH(b.CaseDate) = 1, b.price, 0)) AS Jan,
    SUM(IF(MONTH(b.CaseDate) = 2, b.price, 0)) AS Feb,
    SUM(IF(MONTH(b.CaseDate) = 3, b.price, 0)) AS Mar,
    SUM(IF(MONTH(b.CaseDate) = 4, b.price, 0)) AS Apr,
    SUM(IF(MONTH(b.CaseDate) = 5, b.price, 0)) AS May,
    SUM(IF(MONTH(b.CaseDate) = 6, b.price, 0)) AS Jun,
    SUM(IF(MONTH(b.CaseDate) = 7, b.price, 0)) AS Jul,
    SUM(IF(MONTH(b.CaseDate) = 8, b.price, 0)) AS Aug,
    SUM(IF(MONTH(b.CaseDate) = 9, b.price, 0)) AS Sep,
    SUM(IF(MONTH(b.CaseDate) = 10, b.price, 0)) AS Oct,
    SUM(IF(MONTH(b.CaseDate) = 11, b.price, 0)) AS Nov,
    SUM(IF(MONTH(b.CaseDate) = 12, b.price, 0)) AS Dec
FROM
    tblcontacts a
INNER JOIN
    tblcases b ON a.ContactID = b.ContactAssignedTo
GROUP BY
    a.ContactFullName

基本上,对于每一行,如果casedate属于特定月份,请将price列的值传递给SUM聚合,否则,只需将其传递给0