选择SQL中存在的另一个表上的数据

时间:2012-04-02 04:44:00

标签: sql sql-server sql-server-2008-r2

我有2个表,让第一个表名为“Schedule”,第二个表名为“Setting”。

表“SCHEDULE”

 ID    Name    StartTime    EndTime     Room  
---------------------------------------------
 111   AAAA    08:00        09:00       -
 112   BBBB    08:00        09:00       -
 113   CCCC    08:00        09:00       -
 114   DDDD    08:30        09:30       -
 115   EEEE    08:30        09:30       -   
 116   FFFF    08:30        09:30       -      

表“设置”

 ID    Type    Room  
------------------------
 111     1     BPD01  
 112     2     BPR33  
 113     2     BPR33  
 114     2     BPR35  
 115     2     BPR33  

我希望得到如下结果:

 Room    StartTime  EndTime  Total Used   
---------------------------------------
 BPR33   08:00      09:00    2           
 BPR33   08:30      09:30    1           
 BPR35   08:30      09:30    1               

我的代码如下:

SELECT ST.Room, S.StartTime, S.EndTime, COUNT(*) AS [Total Used]
FROM Schedule AS S CROSS JOIN Setting AS ST
WHERE (ID IN
  (SELECT ID FROM Setting
   WHERE (Type = '2')))
GROUP BY ST.Room, S.StartTime, S.EndTime

但代码导致在设置中显示计数值的所有记录,过滤器无法正常运行。

怎么做?

3 个答案:

答案 0 :(得分:3)

我在这里看到一些潜在的问题:

  • 您的WHERE ID IN (SELECT ID FROM Setting WHERE Type='2')看起来可能只是WHERE Type='2'
  • 您的Type列的数据类型是什么?如果是INT,请执行WHERE Type = 2而不是WHERE Type = '2'(如果Type为VARCHAR,则使用它)。
  • 您似乎没有将两个表连接在一起的JOIN条件(例如WHERE S.ID = ST.ID

现在一起:

SELECT ST.Room, S.StartTime, S.EndTime, COUNT(*) AS [Total Used]
FROM Schedule AS S CROSS JOIN Setting AS ST
WHERE S.ID = ST.ID 
AND Type = 2
GROUP BY ST.Room, S.StartTime, S.EndTime

答案 1 :(得分:2)

SELECT ST.Room, S.StartTime, S.EndTime, COUNT(1) AS [Total Used]
FROM Setting AS ST
LEFT JOIN Schedule AS S 
ON S.ID = ST.ID
WHERE ST.Type = '2'
GROUP BY ST.Room, S.StartTime, S.EndTime

这显示未计划零计数的那些。如果您不希望联接更改为:

SELECT ST.Room, S.StartTime, S.EndTime, COUNT(1) AS [Total Used]
FROM Setting AS ST
JOIN Schedule AS S 
ON S.ID = ST.ID
WHERE ST.Type = '2'
GROUP BY ST.Room, S.StartTime, S.EndTime

答案 2 :(得分:-1)

 SELECT ST.Room,Type AS [Total Used]
    FROM Schedule AS S CROSS JOIN Setting AS ST
    WHERE (ID IN
      (SELECT ID FROM Setting
       WHERE (Type = '2')))
    GROUP BY ST.Room