简体   繁体   中英

SELECT with INNER JOIN to count delta and filter results

I'm trying to select all rows from table B with same id and calculate delta for count value from table A and number of rows selected from B like this:

SELECT A.id, 
       A.count, 
       count(*) AS counter, 
       CAST(count(*) AS SIGNED) - CAST(A.count AS SIGNED) AS delta 
FROM table_A AS A 
INNER JOIN table_B AS B ON B.id = A.id 
GROUP BY A.id

Now i have delta calculated but can't filter results where delta > 0 I've tried to put HAVING delta > 0 and WHERE delta > 0 here and there, but no luck. Looks like i'm missing something with scopes in my query.

Try using this query

SELECT * FROM (SELECT A.id, 
   A.count, 
   count(1) AS counter, 
   CAST(count(1) AS SIGNED) - CAST(A.count AS SIGNED) AS delta 
FROM table_A AS A 
INNER JOIN table_B AS B ON B.id = A.id 
GROUP BY A.id) as t where delta > 0

Is this what you want?

SELECT
    a.id, 
    a.count, 
    COUNT(*) AS counter
FROM cdb_A a
INNER JOIN db_B AS B
    ON b.id = a.id
GROUP BY
    a.id
HAVING
    COUNT(*) > a.count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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