我正在使用2个mysql表。
表1包含员工信息栏:
employee_number,date_of_birth,姓名,地址等
表2有付费信息栏:employee_number(外键),日期,奖金
我的老板要求在屏幕上显示数据,其中日期水平列在顶部,员工垂直列出:
1/1/2000 | 1/1/2001 | 1/1/2002 | 1/1/2003
Bill $500 | $600 | $700 | $900
Ferdie $300 | $500 | $800 | $434
Tony $450 | $234 | $432 | $343
格式化查询的最简单方法是什么,以便数据集采用这种格式?
答案 0 :(得分:2)
您需要的是数据透视表。
MySQL没有内置的方法来创建数据透视表,但您可以手动创建它#34;:
MySQL 5.6架构设置:
create table employees(
employee_number int primary key,
name varchar(50)
);
create table payments(
employee_number int,
bonus_date date,
bonus decimal(8,2)
);
insert into employees values
(1, 'Bill'), (2, 'Freddie'), (3, 'Tony');
insert into payments values
(1, '2000-1-1',500),(1, '2001-1-1',600),(1, '2002-1-1',700),(1, '2003-1-1',900),
(2, '2000-1-1',300),(2, '2001-1-1',500),(2, '2002-1-1',800),(2, '2003-1-1',434),
(3, '2000-1-1',450),(3, '2001-1-1',234),(3, '2002-1-1',432),(3, '2003-1-1',343);
查询1 :
-- 1. Prepare the column definition
select group_concat(distinct
concat(
"sum(case when bonus_date='", bonus_date, "' then bonus else 0 end) as `", bonus_date, "`"
)
)
into @sql
from payments
Results :没有结果
查询2 :
-- 2. Write the full query
set @sql = concat("select e.employee_number, e.name, ", @sql, " from employees as e inner join payments as p on e.employee_number = p.employee_number group by e.employee_number")
Results :没有结果
查询3 :
-- 3. Check the generated query (optional)
-- select @sql
Results :(取消注释以上查询并检查结果)
查询4 :
-- 4. Create a prepared statement using the query you've just created
prepare stmt from @sql
Results :没有结果
查询5 :
-- 5. Execute the prepared statement
execute stmt
<强> Results 强>:
| employee_number | name | 2000-01-01 | 2001-01-01 | 2002-01-01 | 2003-01-01 |
|-----------------|---------|------------|------------|------------|------------|
| 1 | Bill | 500 | 600 | 700 | 900 |
| 2 | Freddie | 300 | 500 | 800 | 434 |
| 3 | Tony | 450 | 234 | 432 | 343 |
查询6 :
-- 6. When you're done, deallocate the prepared statement
deallocate prepare stmt
Results :没有结果
您可以查看my answer on a similar question。
希望这有帮助。