2016-11-04 157 views
0

我有一個包含兩個collumes的數據:Date和Value。我想減去平均每月 - 比方說,九月和十月2016年我foloowing:SQL在一個表中減去兩個不同的平均值

SELECT 'September' as Month, Avg(Values) as Average From myTable 
    where MONTH(Date)='09' and YEAR(Date)='2016' 

SELECT 'October' as Month, Avg(Values) as Average From myTable 
    where MONTH(Date)='10' and YEAR(Date)='2016' 

我無法破解密碼,所以我得到一個單一的表我的數據。

回答

1

我會用有條件聚集:

SELECT Avg(CASE WHEN MONTH(Date) = 9 and YEAR(Date) = 2016 THEN Values END) as sept_avg, 
     Avg(CASE WHEN MONTH(Date) = 10 and YEAR(Date) = 2016 THEN Values END) as oct_avg, 
     (Avg(CASE WHEN MONTH(Date) = 10 and YEAR(Date) = 2016 THEN Values END) - 
     Avg(CASE WHEN MONTH(Date) = 9 and YEAR(Date) = 2016 THEN Values END) 
     ) as difference 
From myTable 
    where 
From myTable 
Where YEAR(Date) = 2016 and MONTH(Date) IN (9, 10); 

注意YEAR()MONTH()回報數字,沒有琴絃,讓你用不應該使用單引號的常量。

0

試試這個,它是確定的結果 SELECT Year,Month , AVG(Values) FROM MyTable WHERE YEAR(Date)='2016' GROUP BY Year,Month

0

SELECT DISTINCT MONTH(日期)爲[月],YEAR(日期)爲[年], AVG(值)OVER(PARTITION BY MONTH(日期),YEAR(日期)) 從表

輸出

Month Year Avg 
9  2010 60 
10 2010 15 

現在你可以寫CTE得到最終的平均差異如下

;with cte as(
SELECT DISTINCT MONTH(Date) as [Month],YEAR(Date) as [Year], 
AVG(Values) OVER(PARTITION BY MONTH(Date),YEAR(Date)) val 
FROM Table 
) 
SELECT DISTINCT t1.val - t2.val FROM cte t1 
       CROSS JOIN cte t2 
       WHERE t1.[Month]=9 AND t2.[Month]=10 
0

請試試這個,它會永久解決你的問題。

SELECT 
     MONTH([current].Date) as Month, avg([current].[Values]) Avgr, ISNULL(avg([current].[Values]), 0) - avg(next.[Values]) as Diff 
FROM  myTable AS [current] 
LEFT JOIN myTable AS [next] 
     ON MONTH([next].Date) = (SELECT MIN(MONTH(Date)) FROM myTable WHERE MONTH(Date) > MONTH([current].Date)) 
GROUP BY MONTH([current].date) 
0

使用PIVOT

順便說一句 - 我建議你不要使用保留的名稱,如「價值」爲列名。

DECLARE @t table(date date, value int) 

INSERT @t values('20160901',20),('20161001',10),('20161001',12) 

;WITH CTE as 
(
    SELECT value, month(date) m, year(date) year 
    FROM @t 
    WHERE date >='2016-09-01' 
    and date < '2016-11-01' 
) 
SELECT year, [10]-[9] difference 
FROM CTE 
PIVOT 
(avg(value) 
FOR m 
in([9],[10]) 
)AS p 

Fiddle