一年内基于分组查询的数据,具有更多分组依据

时间:2018-09-17 21:41:20

标签: sql where

我有一个与此类似的查询:

        SELECT  
        primarylocation
        , secondarylocation
        , COUNT(IDs) as members
        , SUM(observed) as observed
        , SUM(expected) as observed
        , SUM(observed)/SUM(observed) as OE
        FROM table
        WHERE
            *******date >= year(max(date)) - 1 *********
            AND BusinessRuleExcludeFLG = 0
            AND OutlierFLG = 0
        GROUP BY
            primarylocation
            , secondarylocation

我需要为每个主要地点提供一年的数据(因此year(max(date))-1)。上面的问题是,它为每个主要位置和次要位置提供了价值多年的数据。不用CTE就可以在一个查询中做到这一点吗?

1 个答案:

答案 0 :(得分:0)

您实际想要按年份和主要位置分组的声音。

SELECT year(date) year,
       primarylocation,
       count(ids) members,
       sum(observed) observed,
       sum(expected) expected,
       sum(observed) / sum(expected) oe
       FROM table
       WHERE businessruleexcludeflg = 0
             AND outlierflg = 0
       GROUP BY year(date),
                primarylocation;

(我假设oe应该是sum(observed) / sum(expected)而不是sum(observed) / sum(observed),而应该是1。)