1

我的问题是我正在修改现有查询,我不能在查询中使用 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;

看看我想要实现什么?我需要计算 ids,加入 2 个表,但我不能在我的主查询中计算,我不可能复制粘贴所有的“分组依据”条件......我是在 sql 服务器上。

如果我找到答案,我会回来并发布。感谢您对此的任何建议/技巧。

4

2 回答 2

1

以下情况如何:

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
于 2013-10-17T20:22:05.537 回答
0

我遇到了这个:

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;

我得到的结果与我在问题中发布的第一个选择相同,并且没有在任何地方添加“分组依据”,也没有添加很多我不熟悉的内部连接。我会坚持这个解决方案。谢谢!

于 2013-10-18T13:45:57.210 回答