1

可能重复:
SQL“转换”查询

我不知道如何编写 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  
4

2 回答 2

2

这被称为 aPIVOT但 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

结果:

| WEBSITE | BUILDDATE | REVISEDATE | LAUNCHDATE |
-------------------------------------------------
|  Google |  10/30/12 |   11/15/12 |   11/30/12 |
于 2012-11-30T22:21:22.033 回答
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'
于 2012-11-30T22:19:55.950 回答