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

Come ottengo i record correnti in base alla data di entrata in vigore?

Suppongo che ci siano altri modi per farlo, ma penso che funzioni:

DECLARE 
  @OrganizationID varchar(40)

SET @OrganizationID = 'SMESM1HTOVEOVE'

SELECT
  ro.ResourceID,
  ro.OrganizationID,
  max(ro.EffectiveDate)
FROM
  ResourceOrganization ro
WHERE
  ro.OrganizationID = @OrganizationID
GROUP BY
  ro.ResourceID,
  ro.OrganizationID
HAVING
  max(ro.EffectiveDate) = (
    SELECT 
      max(EffectiveDate)
    FROM 
      ResourceOrganization
    WHERE 
      ResourceID = ro.ResourceID)

Ecco un SQLFiddle con cui giocare.

EDIT:In realtà, probabilmente è troppo complicato. Prova questo:

DECLARE 
  @OrganizationID varchar(40)

SET @OrganizationID = 'SMESM1HTOVEOVE'

SELECT
  ro.ResourceID,
  ro.OrganizationID,
  ro.EffectiveDate
FROM
  ResourceOrganization ro
WHERE
  ro.OrganizationID = @OrganizationID
  AND ro.EffectiveDate = (
    SELECT 
      max(EffectiveDate)
    FROM 
      ResourceOrganization
    WHERE 
      ResourceID = ro.ResourceID)