简体   繁体   English

SQL:计算来自两个不同表的两个不同列

[英]SQL: Count two different columns from two different tables

I am trying to get the distinct counts for the resource column of two different tables, then show the comparison for each project ID. 我试图获取两个不同表的resource列的不同计数,然后显示每个项目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). 当然,您将获得相同的计数,即对同一张表的列进行计数(这是由联接完成的,但仍然是一个矩形表)。

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: 首先获取每个项目ID的列表(从表中获取,或者从两个表中解析一个并集解析,但这表明数据库规范化不佳),然后独立查询表的数量:

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

Note: I suppose you a PROJECT table somewhere. 注意:我想您在某处有一个PROJECT表。 I think the best way to do this is with two subqueries. 我认为最好的方法是使用两个子查询。 This way, you will have all your projects, even those without any resources. 这样,您将拥有所有项目,甚至没有任何资源的项目。 Something like: 就像是:

SELECT 
    p.PRJCT_ID,
    ( SELECT COUNT(*) FROM DATA_TABLE_1 t1 WHERE t1.PRJCT_ID = p.PRJCT_ID ) AS TBL1_RSRC_CNT,
    ( SELECT COUNT(*) FROM DATA_TABLE_2 t2 WHERE t2.PRJCT_ID = p.PRJCT_ID ) AS TBL2_RSRC_CNT
FROM PROJECT p
ORDER BY p.PRJCT_ID

You could also use a CASE clause paired with the aggregate SUM function. 您还可以将CASE子句与聚合SUM函数配对使用。

select 
    t1.PRJCT_ID,
    SUM( CASE WHEN t1.RSRC_ID IS NULL THEN 0 ELSE 1 END ) as TBL1_RSRC_CNT,
    t2.PRJCT_ID,
    SUM( CASE WHEN t2.RSRC_ID IS NULL THEN 0 ELSE 1 END ) 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM