通过公共字段组合两个查询组的输出

时间:2013-12-27 08:18:17

标签: sql database oracle

我想结合这两个查询的结果:

SELECT odate, 
       Count(odate), 
       Sum(dur) 
FROM   table1 t1 
GROUP  BY odate 
ORDER  BY odate; 

SELECT cdate, 
       Count(cdate), 
       Sum(dur) 
FROM   table2 t2 
GROUP  BY cdate 
ORDER  BY cdate; 

并得到这样的结果:

odate,t1.count(odate),t2.sum(dur),t2.count(cdate),t2.sum(dur) order by odate

怎么做?

我运行这个时出错:

select odate,count(odate),sum(dur) 
from table1 t1 
group by odate 
order by odate 
union 
select cdate,count(cdate),sum(dur) 
from table2 t2 
group by cdate 
order by cdate;

5 个答案:

答案 0 :(得分:6)

查看您想要的结果,您需要JOIN而不是UNION。你可以这样做

select coalesce(odate, cdate) odate, count1, sum1, count2, sum2
  from
(
  select odate, count(odate) count1, sum(dur) sum1
    from table1
   group by odate
) t1 full join
(
  select cdate, count(cdate) count2, sum(dur) sum2
    from table2
   group by cdate
) t2
    on t1.odate = t2.cdate
 order by odate;

示例输出:

|                          ODATE | COUNT1 |   SUM1 | COUNT2 |   SUM2 |
|--------------------------------|--------|--------|--------|--------|
| January, 01 2013 00:00:00+0000 |      2 |     30 |      2 |     30 |
| January, 02 2013 00:00:00+0000 |      1 |     30 | (null) | (null) |
| January, 03 2013 00:00:00+0000 | (null) | (null) |      1 |     30 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

您正在寻找的是UNION声明。基本上,您接受两个查询并告诉SQL它们可以连接在一起。 最简单的(如果所有字段都是相同的数据类型)将类似于:

select odate,count(odate),sum(dur) from table1 t1 group by odate
UNION
(select cdate,count(cdate),sum(dur) from table2 t2 group by cdate)
ORDER BY odate;

编辑:您的错误位于您放置ORDER BY语句的位置。无论如何,在大多数情况下,无需在UNION内部订购。 有关更多信息,请参阅 http://www.w3schools.com/sql/sql_union.asp

答案 2 :(得分:0)

也许是这样的:

select odate,count(odate),sum(dur) 
from table1 t1 
group by odate
union 
select cdate AS odate,count(cdate),sum(dur) 
from table2 t2 
group by cdate 
order by odate;

答案 3 :(得分:0)

联盟运营商 将两个或多个查询的结果合并到一个结果集中,该结果集包含属于联合中所有查询的所有行。 UNION操作与使用组合来自两个表的列的连接不同。 以下是使用UNION组合两个查询的结果集的基本规则:

所有查询中列的数量和顺序必须相同。

数据类型必须兼容。

select odate,count(odate),sum(dur) from table1 t1 group by odate union
(select cdate,count(cdate),sum(dur) from table2 t2 group by cdate)
ORDER BY odate;

答案 4 :(得分:0)

只需在工会的第二部分重命名日期,并将订单条款放在声明的末尾:

select odate
  ,COUNT(odate)
  ,SUM(dur) 
FROM table1  
GROUP BY odate 
UNION
SELECT cdate odate
  ,COUNT(cdate)
  ,SUM(dur) 
FROM table2  
GROUP BY cdate 
ORDER BY odate