sql >> Database teknologi >  >> RDS >> Sqlserver

Sådan ændres forespørgslen til at give de sidste 15 ugers data i stedet for de sidste 15 dage fra SQL Server

Skift DATEADD fra dag til uge. Derfor to ændringer:

dateadd(week, @LastXDays, l_update)

og

dateadd(week, (@LastXDays + 1), @MaxDate)

I dette tilfælde ville jeg også omdøbe @LastXDays variabel til @LastXWeeks .

CREATE PROCEDURE [dbo].[spGetPlayingTimeOfthepeoplesPerDay] @email NVARCHAR(50)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @MinDate DATE
        ,@MaxDate DATE
        ,@LastXDays INT

    SELECT @LastXWeeks = - 15

    SELECT @MaxDate = peoples.l_update
    FROM peoples
    WHERE peoples.email = @email

    DECLARE @test TABLE (
        quantity VARCHAR(100)
        ,DATE DATE
        ,TimePerDay DECIMAL(5, 2)
        );

    WITH CTE
    AS (
        SELECT peoples.email
            ,peoples.l_update
            ,act.quantity
            ,act.starttime
            ,act.endtime
            ,act.duration AS [Totaltime]
        FROM peoples
        INNER JOIN MPeoples ON peoples.Id = MPeoples.parent_id
        INNER JOIN slines ON MPeoples.id = slines.movesuser_id
        INNER JOIN seg ON slines.id = seg.sline_id
        INNER JOIN act ON seg.id = act.seg_id
        WHERE act.quantity = 'playing'
            AND (peoples.email = @email)
        GROUP BY peoples.email
            ,act.quantity
            ,act.duration
            ,act.starttime
            ,act.endtime
            ,peoples.l_update
        )
    INSERT INTO @test (
        quantity
        ,DATE
        ,TimePerDay
        )
    SELECT quantity
        ,Cast(starttime AS DATE) AS DATE
        ,SUM(datediff(second, starttime, endtime)) / 60.0 AS TimePerDay
    FROM cte WITH (NOLOCK)
    WHERE starttime >= dateadd(week, @LastXWeeks, l_update)
    GROUP BY quantity
        ,cast(starttime AS DATE)

    SELECT @MaxDate = @MaxDate
        ,@MinDate = dateadd(week, (@LastXWeeks + 1), @MaxDate);

    WITH AllDates
    AS (
        SELECT @MinDate AS xDate

        UNION ALL

        SELECT Dateadd(Day, 7, xDate)
        FROM AllDates AS ad
        WHERE ad.xDate < @MaxDate
        )
    SELECT 'playing' AS quantity
        ,ad.xDate
        ,Isnull(t.TimePerDay, 0) AS TimePerDay
    FROM AllDates AS ad WITH (NOLOCK)
    LEFT JOIN @test AS t ON ad.xDate = t.DATE
END

Også et råd:brug ikke forespørgselstip (NOLOCK ), hvis du ikke forstår deres brug. I dette tilfælde skal du bruge NOLOCK kan have katastrofale konsekvenser for dine resultater.

Her er et par artikler, som du bør læse, før du beslutter dig for, om du vil fortsætte med at bruge NOLOCK eller ej.

Forstå SQL Server NOLOCK-tip

Dårlige vaner:Anbringer NOLOCK overalt




  1. Autocommit i Flask-SQLAlchemy

  2. MySQL datoformat snydeark

  3. MySQL Limit LEFT JOIN Underforespørgsel efter tilmelding

  4. Skift stor hjemmeside fra MySQL til MySQLi