简体   繁体   中英

Transform select count(*) inside a inner join

My problem here is that i'm modifying an existing query and i cannot use count(*) in the query. I have to use inner join subqueries.

What i need to "transform" into my inner join is like this (this works):

SELECT count(distinct t1.id)
FROM table1 t1
WHERE t1.column1 = 'value1' AND
      t2.column2 = 'value2' AND
      EXISTS(select 1 from table2 t2 where t2.id = t1.id)

My global query looks like this:

SELECT [many many column]
FROM table2 t2
INNER JOIN [...]
LEFT OUTER JOIN [...]
--[I NEED MY COUNT HERE, see below for example]
WHERE [some conditions are true]
ORDER BY [some column]

What i found to help me is something like this:

SELECT [many many column], myJoin.Count
FROM table2 t2
INNER JOIN (
    SELECT tt2.id, count(distinct tt2.id) as Count
    FROM table2 tt2
    WHERE EXISTS (SELECT 1 FROM table1 tt1 where tt1.id = tt2.id)
    GROUP BY tt2.id) myJoin 
on t2.id = myJoin.id;

See what i'm trying to acheive? I need to count the ids, joining 2 tables, but i can't have a count in my main query, i can't possibly copy-paste all the "group by" condition that would go with it... I'm on sql server.

If i find the answer i will come back and post it. Thanks for any advice/tricks about this.

How about the following:

SELECT table2.*, TopQ.MyCount
  FROM (
    SELECT t2.id, myJoin.MyCount
    FROM table2 t2
    INNER JOIN (
        SELECT tt2.id, count(distinct tt2.id) as MyCount
        FROM table2 tt2
        WHERE EXISTS 
          (SELECT 1 FROM table1 tt1 where tt1.id = tt2.id)
        GROUP BY tt2.id) AS myJoin 
    on t2.id = myJoin.id
)AS TopQ 
INNER JOIN table2 ON TopQ.id = table2.id

I came across this:

select count(distinct t1.id) over (partition by t1.aColumn) as myCount,
       [many many column]
from table2 t2
inner join table1 t1 on [someConditions] = value1 and
                        [someConditions] = value2 and 
                        t2.id = t1.id;

I get the same results as my first select i posted in my question, and without adding a "group by" anywhere and a lot of inner join that im not that familliar with. I'm gonna stick with this solution. Thanks!

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