0

我有 2 个表来收集关于点的事件记录。

CREATE TABLE report_one
(
  date timestamp,
  point_id bigint,
  income int
 )
CREATE TABLE report_two
(
  date timestamp,
  point_id bigint,
  spent int
 )

我想生成一个总和报告(和附加报告)。我想使用 join 因为我需要支持分页,排序......

问题是连接键(报告的点 id)不是 1:1 ,所以我得到的同一行不止一个。

insert into report_one values('2013-1-1',1,1)
insert into report_two values('2013-1-1',1,1)
insert into report_two values('2013-1-2',1,1)

select * from report_one r1 left join report_two r2 on r1.point_id  = r2.point_id

将有 2 行表 report_one ,但总共我只需要一个。我希望能够在表之间创建某种连接的视图,其中每行只有一次。

**我想要这样的输出:

1 (pid) , 1,1,0,0 - 这个来自 report_one

1 (pid) ,0,0,1,1——来自report_two

1 (pid) ,0,0,1,1——来自report_two **

联合都可以很好,但我在两个表中没有相同的列类型。

附言。真正的表有很多列,pk不止一列,我只是为了这个问题而简单

4

3 回答 3

1

为什么不尝试以下。

CREATE TABLE report
(
  report_id bigint,
  date varchar(20),
  point_id bigint,
  amount int,
  amount_type varchar(20)
 );

然后

   insert into report values (1,'2013-01-01',1,1,'income');
   insert into report values (2,'2013-01-01',1,1,'expense');
   insert into report values (2,'2013-01-02',1,1,'expense');

最后

SELECT report_id,amount_type,SUM(point_id) FROM report GROUP BY report_id,amount_type

输出将汇总每个报告/金额类型的 point_id,然后更容易绘制每个日期范围的统计信息等,并且创建表和连接的开销也将最小化。

输出:SQL Fiddle 演示

于 2013-03-03T08:13:12.023 回答
0

我认为这对我有用:

select date d1,point_id p1,0 income ,spent spent from report_one
union ALL
select date d2,point_id p2,income,0 spent from report_two

我不必有零。我为演示添加了它们,因为它们的列不是同一类型

于 2013-03-03T08:20:37.887 回答
0

您可以先按 point_id 对表进行分组,为所需字段选择更合适的聚合函数,然后相互连接:

select r1.point_id, r1.date, r1.income, r2.spent
from
(
   select point_id, max(date) date, sum(income) income
   from report_one
   group by point_id
) r1 
    inner join
    (
       select point_id, max(date) date, sum(spent) spent
       from report_two
       group by point_id
    ) r2 on r1.point_id = r2.point_id

另外,联合方式:

select point_id, date, income sum, 1 is_income
   from report_one
union all
select point_id, date, spent sum, 0 is_income
       from report_two
于 2013-03-03T07:58:49.860 回答