SQL。如何比较两个表中的值,并报告每行结果

时间:2016-09-28 17:18:41

标签: sql teradata

我有两张桌子。 表A

this.httpPostTest().subscribe(
            response => { this.result = response; },
            error => { console.log('ERROR'); },
            () => { console.log('FINISHED')}
);

和表B

id  name    Size
===================
1   Apple   7
2   Orange  15 
3   Banana  22
4   Kiwi    2
5   Melon   28
6   Peach   9

我想要的结果是(在表A中添加一列,这是表B中大小小于大小在表A中的行数)< / p>

id  size
==============
1   14
2   5 
3   31
4   9
5   1
6   16
7   7
8   25

表A和表B都非常庞大。是否有一种聪明的方式来做到这一点。感谢

6 个答案:

答案 0 :(得分:3)

使用此查询有用

SELECT id,
name,
Size,
(Select count(*) From TableB Where TableB.size<Size)
FROM TableA

答案 1 :(得分:2)

获得结果的标准方法是使用非等连接,它将是Explain中的产品连接。首先复制20,000行,然后进行7,000,000 * 20,000次比较,并计算一个巨大的中间线轴。

基于OLAP功能的解决方案通常非常有效:

SELECT dt.*,
   -- Do a cumulative count of the rows of table #2
   -- sorted by size, i.e. count number of rows with a size #2 less size #1   
   Sum(CASE WHEN NAME = '' THEN 1 ELSE 0 end)
   Over (ORDER BY SIZE, NAME DESC ROWS Unbounded Preceding)
FROM
 ( -- mix the rows of both tables, an empty name indicates rows from table #2
   SELECT id, name, size
   FROM a
   UNION ALL
   SELECT id, '', size
   FROM b
 ) AS dt
-- only return the rows of table #1
QUALIFY name <> '' 

如果表#2中有多个具有相同大小的行,您最好在联盟之前计算以减小大小:

SELECT dt.*,
   -- Do a cumulative sum of the counts of table #2
   -- sorted by size, i.e. count number of rows with a size #2 less size #1   
   Sum(CASE WHEN NAME =''  THEN id ELSE 0 end)
   Over (ORDER BY SIZE, NAME DESC ROWS Unbounded Preceding)
FROM
 ( -- mix the rows of both tables, an empty name indicates rows from table #2
   SELECT id, name, size
   FROM a
   UNION ALL
   SELECT Count(*), '', SIZE
   FROM b
   GROUP BY SIZE
 ) AS dt
-- only return the rows of table #1
QUALIFY NAME <> ''

答案 2 :(得分:1)

没有聪明的方法,你只需要加入这样的表:

select a.*, b.size
from TableA a join TableB b on a.id = b.id

要提高性能,您需要在id列上添加索引。

答案 3 :(得分:1)

也许

select 
  id,
  name,
  a.Size, 
  sum(cnt) as sum_cnt
from
  a inner join
  (select size, count(*) as cnt from b group by size) s on
  s.size < a.size
group by id,name,a.size

如果您正在使用大型表格。索引表b的{​​{1}}字段可能有所帮助。我还假设表size中的值会收敛,除了你想要计算它们之外,还有许多你不关心的重复项。

sqlfiddle

答案 4 :(得分:0)

@Ritesh解决方案完全正确,另一个类似的解决方案是使用CROSS JOIN,如下所示

use tempdb
create table dbo.A (id int identity, name varchar(30), size int );
create table dbo.B (id int identity, size int);
go
insert into dbo.A (name, size)
values ('Apple',   7)
,('Orange',    15) 
,('Banana',  22)
,('Kiwi',    2 )
,('Melon',   28)
,('Peach',   6 )

insert into dbo.B (size)
values (14), (5),(31),(9),(1),(16), (7),(25)
go
-- using cross join
select a.*, t.cnt 
from dbo.A
cross apply (select cnt=count(*) from dbo.B where B.size < A.size) T(cnt)

答案 5 :(得分:0)

尝试此查询

SELECT 
A.id,A.name,A.size,Count(B.size) 
from A,B 
where A.size>B.size 
group by A.size 
order by A.id;