按日期交叉方式加入2个表格

时间:2015-06-22 06:21:22

标签: sql sql-server database

我需要以有趣的方式加入2张桌子,请参阅下面的详细信息。表 var bookings = from b in db.Bookings orderby b.PropertyId where b.StartDate.Year == Year group b by b.Property.Title into grp select new { key = grp.Key, cnt = grp.Count() };

PROGRAMS

我还有第二张表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 ........................................................................

Ratings

结果表(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

我不知道如何在SQL中计算它...请告知

2 个答案:

答案 0 :(得分:1)

您可以像这样使用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

答案 1 :(得分:1)

由于我仍然不能100%确定这个问题,我会尽力回答这个问题。

SELECT p.station_int, p.program_name, p.air_date, p.start_Time, p.end_time, p.seq_Num, AVG(r.hh)
FROM programs as p
INNER JOIN ratings as r
    ON r.imp_date = p.imp_date
    AND (r.imp_start_time >= p.start_time
        AND r.imp_start_time <= p.end_time)
    AND (r.imp_end_time <= p.end_time
        AND r.imp_end_time >= p.start_time)
GROUP BY p.station_int, p.program_name, p.air_date, p.start_Time, p.end_time, p.seq_Num

也许这会做你想要的事情。