2

项目清单

我是 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
4

3 回答 3

1

您需要这样将行转换为列:

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。

于 2012-10-17T12:20:42.367 回答
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 的答案的静态版本对所有月份进行硬编码

如果您在具有PIVOT类似于 SQL Server 的功能的 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)
于 2012-10-17T12:24:34.780 回答
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;
于 2012-10-17T12:42:47.517 回答