如何添加子查询以返回相关行的计数

时间:2013-11-15 18:46:19

标签: sql sql-server tsql

我有一个工作的SELECT,它返回每个公司(即订户)的信息。某些描述性数据从“代码”表的内部联接返回。我的问题是如何在结果中添加一个新列,该列是属于每个订户的用户数量的计数。用户表中的SubscriberID是外键:

ALTER TABLE dbo.UserInfo WITH CHECK ADD CONSTRAINT FK_UserInfo_SubscriberID 
  FOREIGN KEY(SubscriberID) REFERENCES dbo.Subscriber (SubscriberID)
  ON UPDATE CASCADE
  ON DELETE CASCADE

我在下面添加了LEFT OUTER JOIN和GROUP BY但是我无法弄清楚为什么解析器会抱怨USubscriberID是一个无效的列名。

SELECT SubscriberID
  ,SubscriberName
  ,DaysUntilExpired
  ,SubscriptionStatus SubscriptionStatusCode
  , C.Description  SubscriptionStatus
  ,U.NumberUsers
FROM dbo.Subscriber S 
    JOIN dbo.CodeValue C ON S.SubscriptionStatus = C.Value
    JOIN dbo.CodeNamespace N ON N.ID = C.CodeNamespaceID AND N.Name = 'SubscriptionStatus'
    JOIN dbo.CodeValue V ON S.NotificationStatus = V.Value
    JOIN dbo.CodeNamespace X ON X.ID = V.CodeNamespaceID AND X.Name = 'NotificationStatus'
LEFT OUTER JOIN (SELECT Count(*) AS NumberUsers FROM dbo.UserInfo) AS U  
ON S.SubscriberID = U.SubscriberID 
GROUP BY 
    S.SubscriberID
  ,SubscriberName
  ,DaysUntilExpired
  ,S.SubscriptionStatus
  ,SubscriptionStatus

2 个答案:

答案 0 :(得分:1)

您可能正在寻找以下内容。您需要内联子查询

SELECT SubscriberID
  ,SubscriberName
  ,DaysUntilExpired
  ,SubscriptionStatus SubscriptionStatusCode
  , C.Description  SubscriptionStatus
  ,(SELECT Count(*) AS NumberUsers FROM dbo.UserInfo where SubscriberID = S.SubscriberID) AS NumberUsers
FROM dbo.Subscriber S 
    JOIN dbo.CodeValue C ON S.SubscriptionStatus = C.Value
    JOIN dbo.CodeNamespace N ON N.ID = C.CodeNamespaceID AND N.Name = 'SubscriptionStatus'
    JOIN dbo.CodeValue V ON S.NotificationStatus = V.Value
    JOIN dbo.CodeNamespace X ON X.ID = V.CodeNamespaceID AND X.Name = 'NotificationStatus'
GROUP BY 
    S.SubscriberID
  ,SubscriberName
  ,DaysUntilExpired
  ,S.SubscriptionStatus
  ,SubscriptionStatus

答案 1 :(得分:1)

Sql抱怨因为您的LEFT OUTER JOIN子查询在列列表中不包含SubscriberId(并且因为您有COUNT聚合而在group by子句中),因此它无法在此列上进行连接。

你应该这样做:

LEFT OUTER JOIN (SELECT SubscriberID , Count(*) AS NumberUsers FROM dbo.UserInfo GROUP BY SubscriberID ) AS U  
ON S.SubscriberID = U.SubscriberID