sql >> Databasteknik >  >> RDS >> Sqlserver

Jämför datumvärden mellan tre kolumner i SQL Server och hämta tillgångsinformation i SQL Server

Använd CASE uttryck för att bestämma det senaste, andra och äldsta datumet. Lägg dem i en CTE och använd kolumnnamnen i WHERE klausul

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. Kan inte binda argument vid index 2 eftersom indexet ligger utanför intervallet

  2. Hibernate och Multi-Tenant Database med hjälp av scheman i PostgreSQL

  3. få en rekursiv föräldralista

  4. mysql ERROR 1064 (42000):Du har ett fel i din SQL-syntax;