Question

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?

Was it helpful?

Solution

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]

OTHER TIPS

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]; 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top