我有两个select语句,都有一些共同的字段。
这是我的表结构:
Id, year, valueA, ValueB
这是我的两个选择陈述
SELECT
id, [year],
SUM(Total_Volume) / (count(distinct(month)) * 7)
FROM
TableA
GROUP BY
id, [year]
和
SELECT
id, [year],
SUM(Total_volume) / (count(distinct(month)) * 5)
FROM
TableA
WHERE
weekday NOT IN ('Friday','Saturday')
GROUP BY
station_id, [year]
我对两个陈述有两个不同的条件。 Id
和year
对于这两个陈述都很常见。
第一个select语句的结果应存储在valueA
列中,第二个select语句的结果应存储在ValueB
中。
任何可能的方法来组合这些查询并将它们作为单个语句插入表中?
答案 0 :(得分:3)
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]
答案 1 :(得分:0)
您可以在单个查询中进行两项计算
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];