我需要在下面运行更大版本的SQL Server 2008查询(SELECT
的42次重复,与下面显示的4次重复相对应)。在我看来,它并不是非常优化的,也是使用while循环的理想候选者,但经过数小时的搜索和尝试后,我无法使其工作。任何人都可以建议更优化的查询来完成我需要的工作吗?
由于
SELECT
t1.Occupied as "1", t2.Occupied as "2",
t3.Occupied as "3", t4.Occupied as "4"
FROM
(SELECT
COUNT(function_id) AS Occupied
FROM
ev_functions
WHERE
room_id = 22
AND DATEADD(HOUR,3,GETDATE()) > from_date_time
AND GETDATE() < to_date_time
AND function_status_id = 6) t1,
(SELECT
COUNT(function_id) AS Occupied
FROM
ev_functions
WHERE
room_id = 1
AND DATEADD(HOUR,3,GETDATE()) > from_date_time
AND GETDATE() < to_date_time
AND function_status_id = 6) t2,
(SELECT
COUNT(function_id) AS Occupied
FROM
ev_functions
WHERE
room_id = 1
AND DATEADD(HOUR,3,GETDATE()) > from_date_time
AND GETDATE() < to_date_time
AND function_status_id = 6) t3,
(SELECT
COUNT(function_id) AS Occupied
FROM
ev_functions
WHERE
room_id = 1
AND DATEADD(HOUR,3,GETDATE()) > from_date_time
AND GETDATE() < to_date_time
AND function_status_id = 6) t4
答案 0 :(得分:0)
在您的情况下,您正在多次访问Same表以进行一小组更改
将SUM
与CASE
一起使用,以避免出现这种情况,并提高可读性
sum(case when room_id = 1 then 1 else 0 end ) as room1,
sum(case when room_id = 22 then 1 else 0 end )..
.....
and so on
from ev_functions
where DATEADD(HOUR,3,GETDATE()) > from_date_time
and GETDATE() < to_date_time
and function_status_id = 6