连接表A和B以获取两者的元素

时间:2016-08-30 00:33:32

标签: sql sql-server tsql sql-server-2012

我有两张桌子:

表'预订':

  id    |    date   | hours
--------------------------
   1    | 06/01/2016 |    2
   1    | 06/02/2016 |    1
   2    | 06/03/2016 |    2
   3    | 06/03/2016 |    4

表' lookupCalendar':

date 
-----
06/01/2016
06/02/2016
06/03/2016

我想将他们加在一起,以便每个预订都有一个日期,以便结果如下:

表'结果':

  id    |    date   | hours
--------------------------
   1    | 06/01/2016 |    2
   1    | 06/02/2016 |    1
   1    | 06/03/2016 |    0  <-- Added by query
   2    | 06/01/2016 |    0  <-- Added by query
   2    | 06/02/2016 |    0  <-- Added by query
   2    | 06/03/2016 |    2
   3    | 06/01/2016 |    0  <-- Added by query
   3    | 06/02/2016 |    0  <-- Added by query
   3    | 06/03/2016 |    4

我尝试过交叉申请,但这并没有让我在那里,也没有完全加入。 FULL JOIN只是在id列中给我空值,而交叉应用给了我太多的数据。

是否有查询可以为我提供上面的results表?

更多信息

注意我这样做可能是有益的,这样我就可以计算时间段内预订的平均小时数,而不仅仅是表格中的记录数。

理想情况下,我能够做到

SELECT AVG(hours) AS my_average, id
FROM bookings
GROUP BY id

但是,因为那只是给我一个记录的计数而不是我希望交叉应用日期的计数。然后我想我可以用results表进行上面的查询。

3 个答案:

答案 0 :(得分:3)

select i.id, c.date, coalesce(b.hours, 0) as hours
  from lookupCalendar c
  cross join (select distinct id from bookings) i
  left join bookings b
    on b.id = i.id
   and b.date = c.date
 order by i.id, c.date

答案 1 :(得分:1)

试试这个:

select c.date, b.id, isnull(b.hours, 0)
from lookupCalendar c
left join bookings b on b.date = c.date

LookupCalendar是您的主要表格,因为您希望针对每个日期进行预订,无论是否在该日期进行预订,因此需要left join

我不确定您是否需要包含b.id来解决您的实际问题。您是不是只想获得这样的每个日期预订的总小时数,然后计算平均值?:

select c.date, sum(isnull(b.hours, 0))
from lookupCalendar c
left join bookings b on b.date = c.date
group by c.date

答案 2 :(得分:0)

您可以尝试加入ID和日期的所有组合,然后继续加入数据;

            MSILTextBox.Clear();
            // Retireve them given the selected index...
            // ... the returned value will be the Tag content of the ...
            // ... previously saved item.
            string getTag= ((ListBoxItem)listBox.SelectedItem).Tag.ToString();
            MSILTextBox.Text = getTag;