簡體   English   中英

轉換內部聯接中的選擇計數(*)

[英]Transform select count(*) inside a inner join

我的問題是我正在修改現有查詢,並且無法在查詢中使用count(*)。 我必須使用內部聯接子查詢。

我需要將“轉換”成我的內部聯接的方式是這樣的(這可行):

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)

我的全局查詢如下所示:

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]

我發現可以幫助我的事情是這樣的:

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;

看到我要達到的目標嗎? 我需要計算ID,加入2個表,但是我無法在主查詢中進行計數,我不可能復制粘貼所有與之匹配的“分組依據”條件...我在sql server上。

如果我找到答案,我會回來並發布它。 感謝您的任何建議/技巧。

怎么樣:

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

我遇到了這個:

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;

我得到的結果與我在問題中發布的第一次選擇的結果相同,並且沒有在任何地方添加“分組依據”以及很多不那么熟悉的內部聯接。 我要堅持這種解決方案。 謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM