sql >> Database teknologi >  >> RDS >> Sqlserver

Find median mellem TO datoer SQL Server 2008

Hvis du mener sættet af startdatoer og slutdatoer, og sæt dem derefter i én kolonne:

WITH t AS (
       SELECT invoice_no, invoice_start_date, invoice_end_date, check_date, status_code,
       FROM INVOICE_HEADER INNER JOIN
            INVOICE_HEADER_CUSTOM
            ON INVOICE_HEADER.invoice_id = INVOICE_HEADER_CUSTOM.invoice_id
       WHERE status_code <> 'REJECTED' AND 
             Check_Date BETWEEN CONVERT(DATETIME, '2014-12-01 00:00:00', 102) AND
             CONVERT(DATETIME, '2014-12-31 00:00:00', 102)
     ), 
     t2 as (
      select d, row_number() over (order by d) as seqnum,
             count(*) over () as cnt
      from (select invoice_start_date as d from t
            union all
            select invoice_end_date as d from t
           ) t
     )
select dateadd(day, datediff(hour, min(d), max(d)) / 2.0, min(d))
from t2
where 2 * seqnum in (cnt, cnt + 1, cnt + 2);


  1. SQL-forespørgsel til gruppering af resultater baseret på rækkefølge

  2. Fordel ved SQL 2008 Linked Server Access Denied Error

  3. Hvordan får man den næste værdi i en sekvens ind i en variabel?

  4. Android SQLite:Hvordan genererer man en stor tabel til testformål?