MySQL SELECT将多个值显示为列

时间:2012-11-30 22:07:16

标签: mysql sql pivot

  

可能重复:
  SQL “transform” query

我无法弄清楚如何编写一个SQL语句来将表的不同值显示为单独的列...这是一个例子:

Table A - Project
= = = = = = = = = = = = = =
ID | Project
= = = = = = = = = = = = = =
1  | Google

Table B - Tasks
= = = = = = = = = = = = = = = = = = = = = = = = = = = =
ID  | Project ID    | Task_name | Date Complete
= = = = = = = = = =  = = = = = = = = = = = = = = = = = =
1   |  1            | Build     | 10/30/12
2   |  1            | Revise    | 11/15/12
3   |  1            | Launch    | 11/30/12

SQL输出格式如下:

Website   | Build Date  | Revise Date   | Launch Date
= = = = = = = = = =  = = = = = = = = = = = = = = = = = =
Google    | 10/30/12    | 11/15/12      | 11/30/12  

2 个答案:

答案 0 :(得分:2)

这称为PIVOT,但MySQL没有PIVOT函数,但您可以使用聚合函数和CASE语句复制它:

select p.project as website,
  max(case when t.task_name = 'build' then date_format(`Date Complete`, '%m/%d/%y') end) BuildDate,
  max(case when t.task_name = 'Revise' then date_format(`Date Complete`, '%m/%d/%y') end) ReviseDate,
  max(case when t.task_name = 'Launch' then date_format(`Date Complete`, '%m/%d/%y') end) LaunchDate
from project p
inner join tasks t
  on p.id = t.`Project ID`
group by p.project

请参阅SQL Fiddle with Demo

结果:

| WEBSITE | BUILDDATE | REVISEDATE | LAUNCHDATE |
-------------------------------------------------
|  Google |  10/30/12 |   11/15/12 |   11/30/12 |

答案 1 :(得分:1)

您可以使用自联接轻松完成此操作:

SELECT DISTINCT
   p.project_id,
   p_build.date_complete As 'Build Date',
   p_revise.date_complete As 'Revise Date',
   p_launch.date_complete As 'Launch Date'
FROM Tasks p
LEFT JOIN Tasks p_revise ON p_revise.project_id = p.project_id 
  AND p_revise.task_name = 'Revise'
LEFT JOIN Tasks p_build ON p_build.project_id = p.project_id
  AND p_build.task_name = 'Build'
LEFT JOIN Tasks p_launch ON p_launch.product_id = p.project_id
  AND p_launch.task_name = 'Launch'