문제

I have two select statements, both having some common fields.

This is my table structure :

Id, year, valueA, ValueB

Here is my two select statements

SELECT 
    id, [year],
    SUM(Total_Volume) / (count(distinct(month)) * 7) 
FROM
    TableA  
GROUP BY
    id, [year]

and

SELECT
    id, [year],
    SUM(Total_volume) / (count(distinct(month)) * 5)
FROM
    TableA  
WHERE 
    weekday NOT IN ('Friday','Saturday') 
GROUP BY 
    station_id, [year]

I have two different conditions for two statements. Id and year is common for both the statements.

Result from first select statement should be stored in column valueA and result from second select statement should be stored in ValueB .

Any possible way to combine these queries and insert them into table as a single statement?

도움이 되었습니까?

해결책

SELECT  a.id ,a.[year],valA,valB
from(
SELECT id ,[year],SUM(Total_Volume)/ (count(distinct(month))*7) valA from TableA  
group by id,[year]) a INNER JOIN

(select id,[year],SUM(Total_volume)/(count(distinct(month))*5) valB
from TableA  
WHERE weekday NOT IN ('Friday','Saturday') 
group by station_id,[year]) b
on a.id=b.id and a.[year]=b.[year]

다른 팁

You could do both the calculation in a single query

SELECT id, 
   [year], 
   Sum(total_volume) / ( Count(DISTINCT( Month)) * 7 ), 
   Sum(CASE 
         WHEN weekday NOT IN ('Friday', 'Saturday' ) THEN 
         total_volume 
         ELSE 0 
       END) / (Count(DISTINCT( Month)) * 5 ) 
FROM   tableA 
GROUP  BY id, 
      [year]; 
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top