SQL:计算两个不同表中的两个不同列

SQL: Count two different columns from two different tables(SQL:计算两个不同表中的两个不同列)
本文介绍了SQL:计算两个不同表中的两个不同列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试获取两个不同表的资源列的不同计数,然后显示每个项目 ID 的比较.现在,此查询为我提供了两个表的相同计数值.

I am trying to get the distinct counts for the resource column of two different tables, then show the comparison for each project ID. Right now, this query gives me the same count values for both tables.

select 
    t1.PRJCT_ID,
    count(t1.RSRC_ID) as TBL1_RSRC_CNT,
    t2.PRJCT_ID,
    count(t2.RSRC_ID) as TBL2_RSRC_CNT
from
    DATA_TABLE_1 t1
LEFT OUTER JOIN 
    DATA_TABLE_2 t2 on t1.PRJCT_ID = t2.PRJCT_ID
GROUP BY
    t1.PRJCT_ID, t2.PRJCT_ID
order by 1

推荐答案

当然你会得到同样的计数,你正在计算同一个表的列(它是由一个连接产生的,授予,但它仍然是一个长方形的桌子).

Of course you're going to get the same count like that, you're counting the columns of the same table (which is made by a join, granted, but it's still a rectangular table).

您想要做的是使用子查询.首先获取每个项目 id 的列表(从一个表中,或解析两个相关表的联合,但这是数据库规范化不良的标志),然后独立查询这些表的计数:

What you want to do is use subqueries. First get a list of every project id (from a table, or an union of parsing both tables in question, but that's a sign of bad database normalization), then query the tables independently for their count:

select p.ID,
  (select count(*) from DATA_TABLE_1 t1 where t1.ID=p.ID) Count1,
  (select count(*) from DATA_TABLE_2 t2 where t2.ID=p.ID) Count2
from projects p

这篇关于SQL:计算两个不同表中的两个不同列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)