sql >> データベース >  >> RDS >> Sqlserver

SQL Server の 3 つの列の日付値を比較し、SQL Server で資産情報を取得する

    CASE を使用 最近、2 番目、および最も古い日付を決定する式。それらを CTE に入れます WHERE で列名を使用します 句

    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
      

    オンライン デモ



    1. GTTテーブル統計とSYS.WRI$_OPTSTAT_TAB_HISTORY

    2. SELECTAS列がWHERE句に存在しません

    3. ORA-01618

    4. other_user_idパラメーターが実行時に機能しない理由はわかりません