我的问题是我正在修改现有查询,我不能在查询中使用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上。
如果我找到答案,我会回来发布。 感谢您对此有任何建议/窍门。
答案 0 :(得分: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
答案 1 :(得分: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;
我得到的结果与我在我的问题中发布的第一个选择相同,并且没有在任何地方添加“group by”和很多内部联接,而不是那个familliar。我会坚持这个解决方案。 谢谢!