sql - 如何在postgresql中将两个不同的表数据合并到一个表中

标签 sql postgresql

我要开发一个报表,需要把employee表和leave表合二为一

Employee Table

employeecode  calldate     doctorvisit 
E001          2017/08/03    Doc001
E002          2017/08/05    Doc002
E003          2017/08/10    Doc003

Leave Table

employeecode    leavedate      leavetype
E001           2017/08/09      casualleave
E002           2017/08/17      sickleave
E003           2017/08/15      casualleve

My output table

employeecode     Dates          fulldetails
E001          2017/08/03           1
E001          2017/08/09       casualleave
E002          2017/08/05           1
E002          2017/08/17        sickleave
E003          2017/08/10           1 
E003          2017/08/15       casualleve

Query

select emp.employeecode,
       case when emp.startdate = emp.startdate then emp.startdate = emp.startdate 
            when lea.calldate = lea.calldate then lea.calldate = lea.calldate  
            else null 
       end as dates,
       case when emp.startdate = emp.startdate then count(doctorvisit) 
            when lea.calldate =lea.calldate then lea.leavetype 
       end as fulldetails 

from employee emp
inner join leave lea on lea.employeecode = emp.employeecode

group by emp.employeecode,emp.calldate,lea.leavedate

当我执行此查询时,它只显示employee 表详细信息而不是leave 详细信息,但我需要这两个详细信息。

所以请帮助我处理这段代码。非常感谢!

最佳答案

这里有一个可能性:

drop table if exists employee;
create table employee(employeecode text, calldate date, doctorvisit text);
insert into employee values
('E001','2017/08/03','Doc001'),
('E002','2017/08/05','Doc002'),
('E003','2017/08/10','Doc003');

drop table if exists leave;
create table leave(employeecode text, leavedate date, leavetype text);
insert into leave values
('E001','2017/08/09','casualleave'),
('E002','2017/08/17','sickleave'),
('E003','2017/08/15','casualleve');

select * from
  (
  select employeecode,calldate as dates,'1' as fulldetails from employee
  union
  select employeecode,leavedate as dates,leavetype as fulldetails from leave
  ) t
order by employeecode,dates;

关于sql - 如何在postgresql中将两个不同的表数据合并到一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47142903/

相关文章:

MySQL删除多表上的行外键?

mysql - 从 MySQL 中的子查询返回一列中的值列表作为文本字符串

java - 异步执行长时间运行的 liquibase 数据库更新

php - 在 DB2 Express C 中跨多个模式使用非限定 SQL

SQL选择连接: is it possible to prefix all columns as 'prefix.*' ?

php - Yii2 批量删除操作发生Internal Server Error

sql - PostgreSQL,获取所有分区表名和所有非分区表名

ruby-on-rails - 在 Postgres 中使用 Rails 数组

sql - 在 SQL Server CE 中替换 DELETE INNER JOIN

php - 这个 SQL 查询有什么问题