需要结合两个SQL查询

时间:2018-12-19 17:29:36

标签: sql sql-server tsql

我想合并两个代码示例。第一个提供了某个时间点在监狱中的人数。

SELECT
    COUNT (Distinct b.BookingNumber)
FROM 
    Booking b
INNER JOIN 
    HousingNodePersonHistory hnph ON b.BookingKey = hnph.BookingKey
INNER JOIN 
    View_Housing vh ON hnph.HousingNodeKey = vh.HousingNodeKey
WHERE 
    b.BookingDateTime <= '2018-08-13 06:23:59.999'
    AND hnph.BeginDateTime <= '2018-08-13 06:23:59.999' 
    AND (hnph.EndDateTime >= '2018-08-13 06:23:59.999' OR hnph.EndDateTime IS NULL OR hnph.EndDateTime = '')
    AND (vh.HousingDescription LIKE '%ACJ%')

第二个返回的日期时间列表,我希望第一个用于为我提供2018年每天的相同人口收益,因此我可以提供2018年更新的平均每日人口数。

DECLARE @StartDate DATETIME = '2018-01-01 00:00:00.000',
        @EndDate   DATETIME = GETDATE();

WITH theDates AS
(
    SELECT 
        @StartDate AS theDate
    UNION ALL
    SELECT 
        DATEADD(DAY, 1, theDate)
    FROM 
        theDates
    WHERE 
        DATEADD(DAY, 1, theDate) <= @EndDate
)   
SELECT 
    theDate
    --,1 as theValue
FROM 
    theDates
OPTION (MAXRECURSION 0)

是否可以使用第二个查询提供的日期填充并在第一个查询的where子句中运行?

2 个答案:

答案 0 :(得分:1)

您可以使用join

WITH theDates AS (
      SELECT @StartDate as theDate
      UNION ALL
      SELECT DATEADD(day, 1, theDate)
      FROM theDates
      WHERE DATEADD(day, 1, theDate) <= @EndDate
     ) 
SELECT d.theDate, COUNT(Distinct b.BookingNumber)
FROM (SELECT d.theDate, DATEADD(minute, d.theDate, 6*60 + 24) as ddhhmm
      FROM thedates d
     ) d CROSS JOIN
     Booking b JOIN
     HousingNodePersonHistory hnph
     ON b.BookingKey = hnph.BookingKey JOIN
     View_Housing vh
     ON hnph.HousingNodeKey = vh.HousingNodeKey
WHERE b.BookingDateTime <= d.ddhhmm AND
      hnph.BeginDateTime <= d.ddhhmm AND
      (hnph.EndDateTime >= d.ddhhmm OR hnph.EndDateTime IS NULL OR hnph.EndDateTime = ''
      ) AND
      vh.HousingDescription LIKE '%ACJ%' 
GROUP BY d.theDate
OPTION (MAXRECURSION 0);

答案 1 :(得分:0)

我可以通过在日历表中添加日期范围并按日期进行过滤来做到这一点。然后,您只需在选择列表中添加StartDate并将其聚合到GROUP BY中即可。

DECLARE @StartDate datetime = '2018-01-01 00:00:00.000'
       ,@EndDate   datetime = GETDATE()

     ;WITH theDates AS
     (SELECT @StartDate as startDate, DATEADD(minute,-1,DATEADD(day,1,@StartDate)) as endDate
      UNION ALL
      SELECT DATEADD(day, 1, startDate) as startDate, DATEADD(minute,-1,DATEADD(day,2,startDate))  as endDate
        FROM theDates
       WHERE DATEADD(day, 1, startDate) <= @EndDate
     )

    Select 
        StartDate = theDates.startDate,  
        BookingCount = COUNT (Distinct b.BookingNumber)
    FROM 
        Booking b
        INNER JOIN HousingNodePersonHistory hnph ON b.BookingKey = hnph.BookingKey
        INNER JOIN View_Housing vh ON hnph.HousingNodeKey = vh.HousingNodeKey
        INNER JOIN theDates D ON b.BookingDateTime BETWEEN D.startDate AND d.endDate 
    WHERE 
        vh.HousingDescription LIKE '%ACJ%'
    GROUP BY
       theDates.StartDate
OPTION (MAXRECURSION 0)