我有一个与此类似的查询:
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就可以在一个查询中做到这一点吗?
答案 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。)