使用 WHILE 循环优化多项选择
Optimising multiple selects with a WHILE loop
我需要 运行 下面 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
在您的情况下,您正在多次访问 Same table 以进行一小部分更改
使用 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
我需要 运行 下面 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
在您的情况下,您正在多次访问 Same table 以进行一小部分更改
使用 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