我正在试图弄清楚如何编写脚本以从一个表中选择某些记录/字段,然后将其连接到另一个表并包含相应计数的列。例如,这就是我现在所拥有的:
select ID, Val from OriginalTable where Something = 1
现在我有另一个表,其中包含链接到此原始表的记录,其中列OriginalID
与ID
的{{1}}匹配。一个例子是:
OriginalTable
...其中3 = select * from OtherTable where OriginalID = 3
的{{1}}。
我想要做的是在第一个语句中添加一个列,该列显示第二个查询中显示的另一个表的计数。例如,这可能是结果集:
ID
如何编写此查询以包含此计数?
答案 0 :(得分:2)
有很多方法可以做到这一点,但您可以使用Group By
select ID, Val, [Count] = count(1)
from OriginalTable be
left join OtherTable ot on be.OriginalID = ot.OriginalID
where Something = 1
group by ID,Val
或者您可以使用OVER
和Partition By
:
select ID, Val, [Count] = count(1) OVER(PARTITION BY ID,Val)
from OriginalTable be
left join OtherTable ot on be.OriginalID = ot.OriginalID
where Something = 1
我个人喜欢OVER
方法。有关MSDN here的信息。
答案 1 :(得分:2)
子查询应该为您处理:
SELECT
ID, Val, Cnt
FROM OriginalTable
JOIN (
SELECT
OriginalID, COUNT(*) AS Cnt
FROM OtherTable
GROUP BY OriginalID
) AS Sub ON ID=OriginalID
答案 2 :(得分:1)
;WITH ot(ID, c) AS
(
SELECT OriginalID, COUNT(*)
FROM dbo.OtherTable
GROUP BY OriginalID
)
SELECT t.ID, t.Val, [Count] = COALESCE(ot.c, 0)
FROM dbo.OriginalTable AS t
LEFT OUTER JOIN ot
ON t.ID = ot.ID
WHERE t.Something = 1;
答案 3 :(得分:1)
SELECT be.ID, be.Val, Count(*) AS [Count]
FROM OriginalTable be
LEFT OUTER JOIN OtherTable ot ON be.ID = ot.OriginalID
WHERE be.Something = 1
GROUP BY be.ID, be.Val