SQL查询JOIN两个没有关系的表

时间:2016-10-06 01:44:31

标签: sql sql-server-2008

我无法使用此表值获取每件物品的每月平均成本记录。 enter image description here

enter image description here

我需要这样的结果:

enter image description here

我想得到的是1月到12月的所有月份,即使该月份没有该项目的交易。

这可能吗?

2 个答案:

答案 0 :(得分:1)

我离开了我的电脑,但我会在概念方面做到以下几点:

  1. 生成一个表/临时表,该表使用事务日期字段中的最小和最大日期。此表至少包含三列:1。月份名称2.该月份的开始日期(如果这样做多年,则为年份)3。结束日期与开始日期的方式相同。 用于第1步的网址:https://www.mssqltips.com/sqlservertip/4054/creating-a-date-dimension-or-calendar-table-in-sql-server/

  2. 从第1步开始加入表格,其中包含开始日期和结束日期之间的交易日期

  3. 最后,分组/平均。

  4. 希望这会有所帮助。明天,如果你仍然需要帮助,我会发布查询。

答案 1 :(得分:1)

在这里(假设是T-SQL):

select b.ItemName, a.MonthName, round(coalesce(avg(c.Cost), 0)) as avg_cost
from table_1 a
join (select ItemName from table_2 group by ItemName) b
on 1 = 1
left join table_2 c
on month(c.TransactionDate) = a.MonthID
and b.ItemName = c.ItemName
group by b.ItemName, a.MonthName
order by b.ItemName, a.MonthID;