按日期显示联接表中的所有行

时间:2013-12-30 23:47:15

标签: sql-server-2008 date join

美好的一天

我一直在努力尝试进行查询...也许不可能在一个简单的查询中做到这一点......也许不是......这就是为什么在几天之后我会来帮助你。

我有7个连接表,但为了简单起见,我们说它们只有2个

TblDeffects
------
Date          IdOperation    Deffects
2013-12-12         1             1
2013-12-12         2             1
2013-12-11         1             1
2013-12-11         3             1
2013-11-10         1             1
2013-11-09         5             1

TblOperations
------
Id    Description
1     Operation 1
2     Operation 2
3     Operation 3
4     Operation 4
5     Operation 5

现在,假设Deffects列表更长,我想加入两个表,按周分开(从星期五开始到星期四结束) 我能做到......我想...... 但我也希望每天从Operations表中获取所有操作...... 所以我可以得到像

这样的东西
Output
------
StartDate          IdOperation    Deffects    Description
2013-12-06            1             2         Operation 1
2013-12-06            2             1         Operation 2
2013-12-06            3             1         Operation 3
2013-12-06            4             0         Operation 4 <- No deffects for this
2013-12-06            5             0         Operation 5 <- No deffects for this

2013-11-08            1             1         Operation 1
2013-11-08            2             0         Operation 2 <- No deffects for this
2013-11-08            3             0         Operation 3 <- No deffects for this
2013-11-08            4             0         Operation 4 <- No deffects for this
2013-11-08            5             1         Operation 5

如果有可能在deffects列中获得0的缺失周数... (空行只是为了分隔几个月,让它在这里更容易阅读)

现在我得到的是两个连接表,最后是未包含的操作(在这种情况下,操作#4带有NULL日期)

是否可以创建类似的查询?

谢谢

1 个答案:

答案 0 :(得分:1)

如果您不想依赖于填充数据的Deffects表,则需要一个包含要检查的日期的临时表。不幸的是,获得这个的唯一方法是循环。

DECLARE @dates TABLE(Date DATETIME NOT NULL UNIQUE)
DECLARE @firstDate DATETIME = '2013-11-08T00:00:00Z'
DECLARE @weeks INT = 7
DECLARE @currentWeek INT = 0
WHILE (@currentWeek < @weeks) BEGIN
  INSERT @dates VALUES (DATEADD(DAY, @currentWeek * 7, @firstDate))
  SET @currentWeek = @currentWeek + 1
END

SELECT Dates.Date, Operations.Id IdOperation, (SELECT COUNT(*) FROM Defects WHERE Defects.date_inspected >= Dates.Date AND Defects.date_inspected < DATEADD(DAY, 7, Dates.Date) AND Defects.id_operation = Operations.Id) AS Deffects, Operations.Description
  FROM @dates Dates
  CROSS JOIN Operations
  ORDER BY Dates.Date DESC

SqlFiddle:http://sqlfiddle.com/#!3/3142db/25

编辑:调整后的代码以匹配提供的sqlFiddle。