基于日期时间值

时间:2017-12-16 01:12:42

标签: sql sql-server subquery

下面我有一个简单的查询来获取今天加入“事件”表和“电影”表的所有电影评级。

Select e.*, m.moviename 
From Event e, movie m 
Where e.eventdate >= DATEADD(day, -1, GETDATE()) 
  and e.moviekey = m.moviekey 
order by e.Ratings desc;

问题

在上面的示例中,您将如何从1周前和1个月前检索评分。因此查询将返回2个额外的列RatingOneMonthAgo,RatingsOneWeekAgo等。

我查看过子查询并且没有点击任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

您可以使用CTEs来提取此信息(类似于使用子查询)。

以下查询假定您每天都有评分,没有重复项(同一天同一部电影的多个评分):

WITH cteOneWeekAgo
AS
(
    SELECT
        moviekey
        , Ratings
    FROM Event
    WHERE CAST(eventdate AS date) = DATEADD(WEEK, -1, CAST(GETDATE() AS date))
)
,

cteOneMonthAgo
AS
(
    SELECT
        moviekey
        , Ratings
    FROM Event
    WHERE CAST(eventdate AS date) = DATEADD(MONTH, -1, CAST(GETDATE() AS date))
)

SELECT
    e.*
    , m.moviename
    , w.Ratings Ratings_OneWeekAgo
    , mth.Ratings Ratings_OneMonthAgo
FROM
    Event e
    JOIN movie m ON e.moviekey = m.moviekey
    LEFT JOIN cteOneWeekAgo w ON e.moviekey = w.moviekey
    LEFT JOIN cteOneMonthAgo mth ON e.moviekey = mth.moviekey
WHERE e.eventdate >= DATEADD(DAY, -1, GETDATE())
ORDER BY e.Ratings DESC

我还写了一个更复杂的查询,如果该日期的评分不存在,它会在您查找的日期之前提取电影的最新评分。

WITH cteOneWeekAgo
AS
(
    SELECT
        moviekey
        , Ratings
        , eventdate
    FROM
        (
            SELECT
                moviekey
                , Ratings
                , eventdate
                , ROW_NUMBER() OVER (PARTITION BY moviekey ORDER BY eventdate DESC) R
            FROM Event
            WHERE CAST(eventdate AS date) <= DATEADD(WEEK, -1, CAST(GETDATE() AS date))
        ) Q
    WHERE R = 1
)
,

cteOneMonthAgo
AS
(
    SELECT
        moviekey
        , Ratings
        , eventdate
    FROM
        (
            SELECT
                moviekey
                , Ratings
                , eventdate
                , ROW_NUMBER() OVER (PARTITION BY moviekey ORDER BY eventdate DESC) R
            FROM Event
            WHERE CAST(eventdate AS date) <= DATEADD(MONTH, -1, CAST(GETDATE() AS date))
        ) Q
    WHERE R = 1
)

SELECT
    e.*
    , m.moviename
    , w.eventdate Ratings_OneWeekAgo_MostRecentDate
    , w.Ratings Ratings_OneWeekAgo
    , mth.eventdate Ratings_OneMonthAgo_MostRecentDate
    , mth.Ratings Ratings_OneMonthAgo
FROM
    Event e
    JOIN movie m ON e.moviekey = m.moviekey
    LEFT JOIN cteOneWeekAgo w ON e.moviekey = w.moviekey
    LEFT JOIN cteOneMonthAgo mth ON e.moviekey = mth.moviekey
WHERE e.eventdate >= DATEADD(DAY, -1, GETDATE())
ORDER BY e.Ratings DESC