需要SQL Server查询语法

时间:2015-07-29 09:36:50

标签: sql-server

我有一种情况,我需要从2个表中提取数据,这是要求

表1

文件名| FileUpLoaded

表2

ID |文件名| InsertedDate

我想获取文件的状态已加载 - 有两个条件 在Filename上加入两个表

  1. FileUpLoaded = 1(已加载)
  2. 今天的ID数量为+/- 10%(某处接近)3天前ID的数量
  3. 这样可以帮助我理解它是否正确加载。

1 个答案:

答案 0 :(得分:0)

这听起来像一组非常奇怪的处理逻辑。您是否了解了您要实现的目标,这可以解释它?我怀疑只是为你编写查询不会提高你的理解力。

也就是说,无论如何,这是大多数情况下的查询,我假设你的表足够小,以至于无需调用WINDOW函数就可以很好地执行:

DECLARE @QueryDate DATETIME = GETDATE();
DECLARE @DaysBefore INT = 3;

SELECT
    FileName    =   Table1.Filename,
    OnThisDay   =   COALESCE(OnQueryDate.Tally, 0),
    BeforeThisDay   =   COALESCE(BeforeQueryDate.Tally, 0)
FROM
    Table1
        OUTER APPLY 
        (
            SELECT Tally = COUNT(1) FROM Table2 WHERE Table2.FileName = Table1.Filename AND 
                Table2.InsertedDate BETWEEN CONVERT(date, @QueryDate) AND DATEADD(DAY, 1, CONVERT(date, @QueryDate))
        ) AS OnQueryDate,
        OUTER APPLY 
        (
            SELECT Tally = COUNT(1) FROM Table2 WHERE Table2.FileName = Table1.Filename AND     
                Table2.InsertedDate BETWEEN DATEADD(DAY,-@DaysBefore,CONVERT(date, @QueryDate) AND CONVERT(date, @QueryDate)
        ) AS BeforeQueryDate
WHERE
    Table1.FileUploaded = 1
    AND
    ... Whatever conditions you want to apply here.