Sqlserver
 sql >> Baza danych >  >> RDS >> Sqlserver

Porównaj wartości dat między 3 kolumnami w SQL Server i pobierz informacje o zasobach w SQL Server

Użyj CASE wyrażenia do określenia ostatniej, drugiej i najstarszej daty. Umieść je w CTE i użyj nazw kolumn w WHERE klauzula

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

DEMO ONLINE



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Zbuduj dynamiczną listę wartości instrukcji INSERT

  2. SQL Server UNION — jakie jest domyślne zachowanie ORDER BY?

  3. Przycinanie T-SQL   (i inne znaki niealfanumeryczne)

  4. Zaawansowane wyszukiwanie z odległościami przy użyciu NHibernate i SQL Server Geography

  5. Wybierz najnowszą grupę rekordów według nazwy użytkownika w SQL Server 2008