显示一个表中的多列

时间:2012-10-17 12:17:45

标签: php sql pivot

列出项目

我是php新手,我正在尝试执行以下操作:

empid  Salary   Month
1      2342     Jan 
1      3234     Feb
1      3445     Mar
2      3222     Jan
2      3342     Feb
3      3352     Mar

如何将其显示为:

empid  jan   feb    mar
1      2342  3234  3445
2      3222  3342  3352

3 个答案:

答案 0 :(得分:1)

您需要将 pivot 行划分为如下列:

SELECT
  emp_id,
  MAX(CASE WHEN month_end = 'jan' THEN salary END) 'jan',
  MAX(CASE WHEN month_end = 'feb' THEN salary END) 'feb',
  MAX(CASE WHEN month_end = 'mar' THEN salary END) 'mar'
FROM Emps
GROUP BY emp_id

这是执行此操作的标准方法。它应该适用于所有RDBMS。

答案 1 :(得分:0)

您没有指定您的RDBMS,但如果您使用的是MySQL并且您返回的值的数量未知,则使用预准备语句:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'sum(case when month_end = ''',
      month_end,
      ''' then salary end) AS ',
      month_end
    )
  ) INTO @sql
FROM yourTable;

SET @sql = CONCAT('SELECT Emp_Id, ', @sql, ' 
                    FROM yourtable 
                    GROUP BY Emp_Id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

或者您可以通过类似于@ Mahmoud答案的静态版本对所有月份进行硬编码

如果您正在使用具有类似于SQL Server的PIVOT功能的RDBMS,那么您可以使用以下内容:

select *
from
(
    select emp_id, salary, month_end
    from yourtable
) x
pivot
(
    max(salary)
    for month_end in ([jan], [feb], [mar])
) p

或者使用动态sql:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(month_end) 
                    from yourtable
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT emp_id, ' + @cols + ' from 
             (
                select emp_id, salary, month_end
                from yourtable
            ) x
            pivot 
            (
                max(salary)
                for month_end in (' + @cols + ')
            ) p '

execute(@query)

答案 2 :(得分:0)

SELECT emp_id AS emp_id , 
[jan], [feb], [mar]
FROM
(SELECT month_end , salary 
    FROM Emps) AS SourceTable
PIVOT
(
AVG(salary )
FOR month_end IN ([jan], [feb], [mar])
) AS PivotTable;