-1

我试图弄清楚如何编写脚本以从一个表中选择某些记录/字段,然后将其连接到另一个表并包含相应计数的列。例如,这就是我现在所拥有的:

select ID, Val from OriginalTable where Something = 1

现在我有另一个表,其中包含链接到该原始表的记录,其中 a列OriginalIDID. OriginalTable一个例子是:

select * from OtherTable where OriginalID = 3

...其中 3 =IDOriginalTable

我想要做的是在第一个语句中添加一个列,该列显示另一个表的计数,如第二个查询中所示。例如,这可能是一个结果集:

ID    Val    Count
1     abc    15
2     def    23
3     ghi    42
4     jkl    19

如何编写此查询以包含此计数?

4

4 回答 4

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

或者你可以使用OVERand 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 上的信息。

于 2012-08-14T15:28:00.667 回答
2

子查询应该为您处理:

SELECT 
  ID, Val, Cnt
FROM OriginalTable
JOIN (
  SELECT 
    OriginalID, COUNT(*) AS Cnt
  FROM OtherTable
  GROUP BY OriginalID
  ) AS Sub ON ID=OriginalID
于 2012-08-14T15:29:39.010 回答
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;
于 2012-08-14T15:28:11.520 回答
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
于 2012-08-14T15:29:12.860 回答