问题
I have table with following rows.
table1:
id col1 col2 date
1 ttx 123 13-05-2020
2 abc 436 13-05-2020
1 ccy 879 13-05-2020
below is the main table which has historical records.
table2:
date col1 col3 col4
13-05-2020 xyz ttx 1
13-05-2020 xyz abc 2
13-05-2020 xyz ccy 3
--------
13-05-2019 xyz ttx 1
13-05-2019 xyz abc 2
13-05-2019 xyz ccy 3
col1
of table 1 and col3
of table 2 have similar data.
I have to calculate average for all ids like :
to get value for matched date and previous year date like for Id=1
, below col4
will be picked.
date col1 col3 col4
13-05-2020 xyz ttx 1
13-05-2019 xyz ttx 1
average 1+1/2=1
expected output:
id col1 col2 date average
1 xyz 123 13-05-2020 1
2 abc 436 13-05-2020 2
1 ccy 879 13-05-2020 3
I am trying with joining table but not sure how to select previous year date:
SELECT id, col1, col2, date
, t2.col4 + /2 As 'average'
FROM table1 t1
JOIN table2 t2 on t1.date = t2.date
Any idea how to start/go ahead to get expected output?
回答1:
I might be misunderstanding, but I think it would be better to JOIN on id, or whichever value you want to calculate the average over, and then use a GROUP BY on the date column. Then you could use the AVG function to let SQL do the work of calculating the averages.
Some documenation on calculation the average: https://docs.microsoft.com/en-us/sql/t-sql/functions/avg-transact-sql?view=sql-server-ver15
回答2:
This query should give you the desired output:
SELECT MAX(T1.ID) as ID, MAX(T1.Col1) as Col1,
MAX(T1.Col2) as Col2, MAX(T1.[date]) as date,
AVG(T2.Col4) as [average]
FROM TABLE1 T1
INNER JOIN TABLE2 T2
ON T1.Col1 = T2.Col3
GROUP BY T1.Col1
来源:https://stackoverflow.com/questions/61769476/create-a-query-to-loop-through-when-there-are-no-matching-condition-in-sql