简体   繁体   English

转换内部联接中的选择计数(*)

[英]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. 我的问题是我正在修改现有查询,并且无法在查询中使用count(*)。 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. 我需要计算ID,加入2个表,但是我无法在主查询中进行计数,我不可能复制粘贴所有与之匹配的“分组依据”条件...我在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! 谢谢!

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

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