sql >> Database >  >> RDS >> Sqlserver

Max binnen een tijdsbestek met dubbele datum

Als ik het goed heb begrepen, wil je afzonderlijke vermeldingen tellen voor een specifieke status in je tijdsperiode... als dat zo is, moet je de DISTINCT gebruiken clausule in uw count() veranderen van count(*) naar count(distinct Entry_id)

with c (Status_Id, Entry_Id, Start_Date) AS (
  select Status_Id, Entry_Id, Start_Date from tbl where
  (End_Date BETWEEN '19000101' AND '21000101')
  AND ((Start_Date BETWEEN '19000101' AND '21000101')
  OR End_Date <= '21000101'))
select Status_Id, count(distinct Entry_Id) as cnt from 
 (select Entry_Id, max(start_date) as start_date from c
  group by Entry_Id) d inner join
c on c.Entry_Id = d.Entry_Id
and c.start_date = d.start_date
GROUP BY Status_Id WITH ROLLUP

BEWERKEN

Zolang het je niet uitmaakt welke status retour is voor een bepaald item, denk ik dat je de innerlijke vraag kunt wijzigen om de eerste Status te retourneren en ook lid te worden van de status

with c (Status_Id, Entry_Id, Start_Date) AS (
  select Status_Id, Entry_Id, Start_Date from tbl where
  (End_Date BETWEEN '19000101' AND '21000101')
  AND ((Start_Date BETWEEN '19000101' AND '21000101')
  OR End_Date <= '21000101'))
select c.Status_Id, count(c.Entry_Id) as cnt from 
 (select Entry_Id, Start_Date, (select top 1 Status_id from c where Entry_Id = CC.Entry_Id and Start_Date = CC.Start_Date) as Status_Id
  from (select Entry_Id, max(start_date) as start_date from c
  group by Entry_Id) as CC) d inner join
c on c.Entry_Id = d.Entry_Id
and c.start_date = d.start_date
and c.status_id = d.status_id
GROUP BY c.Status_Id

Resultaat

Status_id Count
 489       2
 492       1
 495       1


  1. Willekeurige id's in sqlalchemy (pylonen)

  2. android JDBC mysql java connector app:preDexDebug

  3. verbind R met MySQL met RODBC met behulp van dsn

  4. mysqlworkbench geeft een versiefout bij het exporteren van de database