-5

我在表中有数据

在此处输入图像描述

我想要上个月的消费和最近三个月的消费

例如基于阅读

在此处输入图像描述

我试过这个:

SELECT tbl.CustomerID
    ,tbl.CustomerName
    ,tbl2.Last3Months
    ,tbl.LastMonth
FROM (
    SELECT events.event_item_id CustomerID
        ,items.item_name CustomerName
        ,MAX(events.event_additional_info) maxR
        ,MIN(events.event_additional_info) minR
        ,(MAX(events.event_additional_info) - MIN(events.event_additional_info)) AS LastMonth
    FROM events
    INNER JOIN items ON events.event_item_id = items.item_id
    WHERE (events.event_additional_info <> '0.000000')
        AND (
            events.event_timestamp BETWEEN '08-MAY-15 12:00:00 AM'
                AND '08-Jun-15 6:21:59 PM'
            )
    GROUP BY events.event_item_id
        ,items.item_name
    ) tbl
    ,(
        SELECT events.event_item_id CustomerID
            ,items.item_name CustomerName
            ,MAX(events.event_additional_info) maxR
            ,MIN(events.event_additional_info) minR
            ,(MAX(events.event_additional_info) - MIN(events.event_additional_info)) AS Last3Months
        FROM events
        INNER JOIN items ON events.event_item_id = items.item_id
        WHERE (events.event_additional_info <> '0.000000')
            AND (
                events.event_timestamp BETWEEN '08-MAR-15 12:00:00 AM'
                    AND '08-Jun-15 6:21:59 PM'
                )
        GROUP BY events.event_item_id
            ,items.item_name
        ) tbl2
WHERE tbl2.CustomerID = tbl.CustomerID
4

1 回答 1

0

你没有提供模式,所以我从这个开始工作:

DECLARE @MeterReading TABLE( ID INT, ReadingDate DateTime, Reading MONEY)

SQLDateDiff函数是关键。给定“截至”日期的输入(可以默认通过GETDATE(),您可以获得上个月(DATEDIFF = 0)和第 0、1 和 2 个月(因此为 3 个月)内的读数。

第一个查询(在 WITH 子句中)都将数据限制为 3 个月,并找到每个月的最大值/最小值。

最后的查询非常简单

DECLARE @ASOF DateTime = GETDATE();  -- semicolon is important here!

WITH monthreadinds as (SELECT id
                        , DATEDIFF(MONTH,mr.ReadingDate , @ASOF) as WhichMonthAgo
                        , MIN(reading) as MinReading
                        , max(reading) as MaxReading
                    FROM @MeterReading mr
                    WHERE DATEDIFF(MONTH,mr.ReadingDate , @ASOF)  <= 2  -- very important (limits to 3 months)
                    group by ID, DATEDIFF(MONTH,mr.ReadingDate , @ASOF) 
                    )
SELECT id,
    SUM( CASE WHEN mr.WhichMonthAgo = 0 THEN mr.MaxReading -  mr.MinReading  ELSE 0 END ) as LastMonthConsumption,
    MAX(mr.MaxReading) -  MIN(mr.MinReading)   as Last2MonthsConsumption
FROM  monthreadinds mr
GROUP by id 
于 2015-06-08T16:08:03.553 回答