sql – 按日期交叉方式连接2个表

我需要以一种有趣的方式加入2张桌子,请看下面的详细信息.表程序:

STATION_INT | PROGRAM_NAME | AIR_DATE | START_TIME | END_TIME | SEQ_NUM
========================================================================
          1      '70S SHOW '  5/6/2015    32405000   32410000         1
          1      '80S SHOW '  5/6/2015    32415000   34300000         1  
........................................................................

我还有第二个表评级

STATION_INT | IMP_DATE | IMP_START_TIME | IMP_END_TIME | IMP_STATUS |   HH | F2_5   
==================================================================================
         1     5/6/2015        32400000       34199000           S    1422   8464
         1     5/6/2015        32400000       34199000           F    1677   9000
         1     5/6/2015        34199000       34310000           S    1522   9160
...................................................................................

结果表(PROGRAMS * RATINGS)应该是这样的:

STATION_INT | PROGRAM_NAME | AIR_DATE | START_TIME | END_TIME | SEQ_NUM | IMP_DATE | IMP_START_TIME | IMP_END_TIME | HH_S | HH_F | F2_5_S | F2_5_F
========================================================================================================================================================
         1       '70S SHOW '  5/6/2015    32405000    32410000        1   5/6/2015         32400000       34199000   1422   1677     8464     9000    
         1       '80S SHOW '  5/6/2015    32415000    34300000        1   5/6/2015         32400000       34310000 (1422+1522)/2  --- (8464+9160)/2  ---

我不知道如何在SQL中计算它…请指教

最佳答案 你可以像这样使用CROSS APPLY和条件聚合.

询问

SELECT * 
FROM PROGRAMS as P
CROSS APPLY (
SELECT 
    AVG(CASE WHEN R.IMP_STATUS = 'F' THEN HH END) as AVG_F_HH,
    AVG(CASE WHEN R.IMP_STATUS = 'F' THEN F2_5 END) as AVG_F_F2_5,
    AVG(CASE WHEN R.IMP_STATUS = 'S' THEN HH END) as AVG_S_HH,
    AVG(CASE WHEN R.IMP_STATUS = 'S' THEN F2_5 END) as AVG_S_F2_5
FROM Ratings as R 
WHERE R.IMP_DATE = P.AIR_DATE AND R.STATION_INT = P.STATION_INT
AND NOT
(R.IMP_START_TIME >= P.END_TIME OR P.START_TIME >= R.IMP_END_TIME)
) as R

产量

STATION_INT PROGRAM_NAME    AIR_DATE    START_TIME  END_TIME    SEQ_NUM AVG_F_HH    AVG_F_F2_5  AVG_S_HH    AVG_S_F2_5
1   70S SHOW    May, 06 2015 00:00:00   32405000    32410000    1   1677    9000    1422    8464
1   80S SHOW    May, 06 2015 00:00:00   32415000    34300000    2   1677    9000    1472    8812

SQL Fiddle

点赞