SQL - 两张表之间的区别计数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SQL - 两张表之间的区别计数相关的知识,希望对你有一定的参考价值。
我对我认为是比较简单的剧本有一个思维上的误区。希望是我把逻辑想得太简单了。
我想做的是在一个不同的列上执行两个计数,这个列是直连的。
我想要的是
count(a.book_id) as count_of_books
count(b.book_ref_number) as count_of_losses
预期输出
--------------------------------------------------------
| Book | count_of_books | count of losses|
--------------------------------------------------------
|Hunger Games | 76 | 31 |
--------------------------------------------------------
|Hop on Pop | 27 | 6 |
--------------------------------------------------------
|Pout Pout Fish | 138 | 43 |
--------------------------------------------------------
我已经尝试了几个不同的脚本。以下是我试过的两个脚本。
(select count(*) from Inventory_Table x ) Count1,
(select count(*) from Loss_table b ) Count2
from Inventory_Table x
right join Loss_table b on b.book_ref_number = x.book_id
where rownum < 20
select
a.book_name,
count(distinct a.book_id),
count(b.book_ref_number)
from Inventory_Table x
right join Loss_table b on trim(b.book_ref_number) = trim(a.book_id)
我得到的结果
--------------------------------------------------------
| Book | count_of_books | count of losses|
--------------------------------------------------------
|Moby Dick | 4376 | 2574 |
--------------------------------------------------------
请大家指点一下我的疏忽错误。先谢谢你
and rownum <20
你把结果集限制在20条记录上。
试试这个
select * from (
select
a.mrch_Nr,
count(distinct a.fdr_trac_nr),
count(b.auth_id)
from DATASTORE_FD.DEB_CRD_AUTH_LOG_REC a
right join jordab26.ft b on trim(b.auth_id) = trim(a.fdr_trac_nr)
where a.auth_log_dt between '20200101' and '20200408'
group by a.mrch_nr
)
where rownum < 20
试试这个,我不确定 rownum < 20
. 另外,确保你添加正确的条件组。
select sum(case book_id when null then 0 else 1 end ) count_of_books,
sum(case book_ref_number when null then 0 else 1 end ) count_of_losses
from Inventory_Table x
right join Loss_table b on b.book_ref_number = x.book_id
where rownum < 20
这是你想要的吗?
Select distinct bookname,
count(distinct
a.bookid)+sum(
case when a.bookid IS NULL
THEN 1 END) ,
count(distinct b.id) as lossid
From inventary_table a
Left Join
Loss_table b
On
a.bookid=b.book_ref_number
SELECT book_name,COUNT(book_id),COUNT(book_ref_id) FROM Inventory_Table right join Loss_table on book_ref_number = book_id GROUP BY book_name。
但是如果你需要库存中的所有账本,而只需要Loss_table中的匹配账本,那么就应该采用左连接。
SELECT book_name,COUNT(book_id),COUNT(book_ref_id) FROM Inventory_Table leftjoin Loss_table on book_ref_number = book_id GROUP BY book_name
0
SELECT book_name,COUNT(book_id),COUNT(book_ref_id) FROM Inventory_Table right join Loss_table on book_ref_number = book_id GROUP BY book_name。
以上是关于SQL - 两张表之间的区别计数的主要内容,如果未能解决你的问题,请参考以下文章
谁可以给个sqlserver2005两张表之间的递归查询,我看网上都是一张表两个字段之间递归查询.