在SQL Server中进行子选择

时间:2014-11-14 10:20:45

标签: sql sql-server

我想为列创建一个子选择,具有特定的计数。

通常这不是问题,但在这种情况下,我需要将当前列的ID作为过滤器。

例如,我有一个表Rooms

RoomID  Name 
---------------
  1     Room 1
  2     Room 2
  3     Room 3

所有房间都有客户,例如

ClientID   RoomID   ClientName
-------------------------------
   1         1      Client1
   2         1      Client2
   3         2      Client3

还有一个ClientUsage表,例如

ID ClientID StateID
-------------------
1     1       1
2     2       1
3     3       0

现在我要显示所有房间,包括所有客户的数量(例如StateID = 1

结果应为:

ID, RoomID, CountOfClients, CountOfClientsWithStateID = 1

前三件事很容易,使用这个:

SELECT 
    ID, Name,
    (SELECT COUNT(*) AS Count
     FROM Client
     WHERE (RoomID = T1.ID)) AS ClientCount
FROM  
    Room AS T1

但现在我需要Client.ID作为参考来获取状态 - 任何想法如何解决?

尝试使用类似的东西,但这不起作用:

SELECT 
    ID, Name,
    (SELECT COUNT(*) AS Count
     FROM Client AS T2
     WHERE (RoomID = T1.ID)) AS ClientCount,
    (SELECT COUNT(*) AS Count
     FROM ClientUsage
     WHERE (ClientUsage.ClientID = T2.ID) AND (StateID = 1)) AS ClientFreeCount
FROM 
    Room AS T1

提前致谢

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

SELECT ID, Name,
       (SELECT COUNT(*) AS Count
          FROM Client AS T2
         WHERE (RoomID = T1.ID)) AS ClientCount,
       (SELECT COUNT(*) AS Count
          FROM ClientUsage
          JOIN Client ON ClientUsage.ClientID = Client.ID
         WHERE (StateID = 1)
           AND (Client.RoomID = T1.ID)
       ) AS ClientFreeCount
  FROM Room AS T1

答案 1 :(得分:1)

  SELECT id AS ClientUsageID, 
                roomid AS RoomID, 
                count(cliendid) AS CountClientID,
                StateID AS CountOfClientsWithStateID 
  FROM room R join client C
    ON R.RoomID  =C.RoomID  
    join ClientUsage  CL
    on C.ClientID   =CL.ClientID  
    where StateID=1