sql >> Database >  >> RDS >> Sqlserver

Vergelijk datumwaarden tussen 3 kolommen in SQL Server en haal informatie over activa op in SQL Server

Gebruik CASE uitdrukkingen om de recente, tweede en oudste datum te bepalen. Zet ze in een CTE en gebruik de kolomnamen in de WHERE clausule

WITH CTE AS(
    SELECT *,
        RecentDate =
            CASE
                WHEN APPR_DATE_1 >= APPR_DATE_2 AND APPR_DATE_1 >= APPR_DATE_3 THEN APPR_DATE_1
                WHEN APPR_DATE_2 >= APPR_DATE_3 AND APPR_DATE_2 >= APPR_DATE_1 THEN APPR_DATE_2
                WHEN APPR_DATE_3 >= APPR_DATE_2 AND APPR_DATE_3 >= APPR_DATE_1 THEN APPR_DATE_3
            END,
        SecondDate =
            CASE
                WHEN APPR_DATE_1 BETWEEN APPR_DATE_2 AND APPR_DATE_3 OR APPR_DATE_1 BETWEEN APPR_DATE_3 AND APPR_DATE_2 THEN APPR_DATE_1
                WHEN APPR_DATE_2 BETWEEN APPR_DATE_1 AND APPR_DATE_3 OR APPR_DATE_1 BETWEEN APPR_DATE_3 AND APPR_DATE_1 THEN APPR_DATE_2
                WHEN APPR_DATE_3 BETWEEN APPR_DATE_1 AND APPR_DATE_2 OR APPR_DATE_1 BETWEEN APPR_DATE_2 AND APPR_DATE_1 THEN APPR_DATE_3
            END,
        OldestDate =
            CASE
                WHEN APPR_DATE_1 <= APPR_DATE_2 AND APPR_DATE_1 <= APPR_DATE_3 THEN APPR_DATE_1
                WHEN APPR_DATE_2 <= APPR_DATE_3 AND APPR_DATE_2 <= APPR_DATE_1 THEN APPR_DATE_2
                WHEN APPR_DATE_3 <= APPR_DATE_2 AND APPR_DATE_3 <= APPR_DATE_1 THEN APPR_DATE_3             
            END
    FROM #ASSET
)
SELECT
    APPR_DATE_1, APPR_DATE_2, APPR_DATE_3, ID, NAME, ADDRESS 
FROM CTE
WHERE
    DATEDIFF(DAY, SecondDate, RecentDate) > 365
    OR DATEDIFF(DAY, OldestDate, SecondDate) > 365

ONLINE DEMO



  1. Er is iets mis met de Hibernate DB-verbindingspooler c3p0

  2. Oracle DBMS - Lees een tabel voor verwerking Updaten in een AFTER-trigger - tabel muteren

  3. ActiveAndroid Pre-tabel vullen met schemamigratie

  4. MySQL naar PostgreSQL-tabel maak conversie - tekenset en sortering