在没有连接的情况下将一个表中的不同值循环到另一个表

时间:2015-06-22 18:11:41

标签: sql sql-server tsql while-loop

我知道循环在SQL中并不理想,但我想不出另一种方法。

我希望表1中的每个不同的行在表2中生成每个不同的日期和小时。

换句话说,表2的日期为2014年1月1日至2015年4月30日,每个不同的日期有24行,每天一小时。我现在希望表1中的每个不同的行在表2中具有每个不同的日期,其中每个日期都是24小时。

表1:

DROP TABLE Baylor_Raw..MEDICAL_SERVICE_DESC
SELECT MEDICAL_SERVICE_DESC 
INTO Baylor_Raw..MEDICAL_SERVICE_DESC
FROM Baylor_Raw..Raw_ADT 
WHERE MEDICAL_SERVICE_DESC IS NOT NULL AND MEDICAL_SERVICE_DESC NOT IN ('#N/A','CANCEL','DAY SURGERY','HOSPICE','INFUSION')

表2:

DECLARE @DATE DATE
SET @DATE = '05/01/2014'

DECLARE @HOUR INT
SET @HOUR = 0

DROP TABLE Baylor_Raw..DateTable
CREATE TABLE Baylor_Raw..DateTable
    (DATE_OF_DISCHARGE DATE
    ,HOUR_OF_DISCHARGE INT)


WHILE @DATE<'05/01/2015' BEGIN
    WHILE @HOUR<25 BEGIN
        INSERT INTO Baylor_Raw..DateTable (DATE_OF_DISCHARGE,HOUR_OF_DISCHARGE)
        VALUES (@DATE,@HOUR)
        SET @HOUR = @HOUR+1
    END
    SET @DATE = DATEADD(DD,1,@DATE)
    SET @HOUR = 0
END

以下尝试不起作用。在运行时间超过几分钟后我取消了。

DECLARE @MEDICAL_SERVICE_DESC NVARCHAR(255)
SET @MEDICAL_SERVICE_DESC = (SELECT MIN(MEDICAL_SERVICE_DESC) FROM Baylor_Raw..MEDICAL_SERVICE_DESC)

DECLARE @DATE DATE
SET @DATE = '05/01/2014'

DECLARE @HOUR INT
SET @HOUR = 0

DROP TABLE Baylor_Raw..DateTable
CREATE TABLE Baylor_Raw..DateTable
(MEDICAL_SERVICE_DESC NVARCHAR,
DATE_OF_DISCHARGE DATE
,HOUR_OF_DISCHARGE INT)

WHILE @MEDICAL_SERVICE_DESC IS NOT NULL BEGIN
    WHILE @DATE<'05/01/2015' BEGIN
        WHILE @HOUR<25 BEGIN
            INSERT INTO Baylor_Raw..DateTable (MEDICAL_SERVICE_DESC,DATE_OF_DISCHARGE,HOUR_OF_DISCHARGE)
            VALUES (@MEDICAL_SERVICE_DESC,@DATE,@HOUR)
            SET @HOUR = @HOUR+1
        END
        SET @DATE = DATEADD(DD,1,@DATE)
        SET @HOUR = 0
    END
DELETE FROM Baylor_Raw..MEDICAL_SERVICE_DESC WHERE MEDICAL_SERVICE_DESC = @MEDICAL_SERVICE_DESC
SET @MEDICAL_SERVICE_DESC = (SELECT MIN(MEDICAL_SERVICE_DESC) FROM Baylor_Raw..MEDICAL_SERVICE_DESC)
SET @DATE = '05/01/2014'
END

2 个答案:

答案 0 :(得分:0)

所以你希望table1中的所有不同记录与table2中的所有记录配对?这是一个交叉连接:

select *
from (select distinct * from table1) t1
cross join table2;

或者您希望它们与日期相关吗?内联:

select *
from (select distinct * from table1) t1
inner join table2 t2 on t1.date = t2.date;

答案 1 :(得分:0)

通过首先使用循环构建日期和小时列表,然后使用交叉连接将其与服务名称组合,可能会获得更好的性能,如下所示。您可能需要稍微调整一下,因为您了解源数据:

DECLARE @dates TABLE (DATE DATE)
DECLARE @hours TABLE (hours INT)
DECLARE @hour INT
    ,@date DATE

SET @hour = 0
SET @date = '05/01/2014'

WHILE (@hour < 25)
BEGIN
    INSERT INTO @hours
    SELECT @hour

    SET @hour = @hour + 1
END

WHILE (@ DATE < '05/01/2015')
BEGIN
    INSERT INTO @dates
    SELECT @date

    SET @DATE = DATEADD(DD, 1, @DATE)
END

INSERT INTO Baylor_Raw..DateTable (
    MEDICAL_SERVICE_DESC
    ,DATE_OF_DISCHARGE
    ,HOUR_OF_DISCHARGE
    )
SELECT MEDICAL_SERVICE_DESC
    ,DATE
    ,hour
FROM Baylor_Raw..MEDICAL_SERVICE_DESC
CROSS JOIN @date d
CROSS JOIN @hours h