2017-08-17 76 views
1

我正在嘗試將交易日期排序爲老化策略。當LastDate已經位於大於Aging Days限制政策的位置時,它應該顯示爲OverAge,如果不是Within指的是當前日期。 這是當前表:SQL-Case當問題

+---------+------+----------+-------------+ 
|LastDate | Part | Location | Aging Days | 
+---------+------+----------+-------------+ 
12/1/2016 123 VVV   90 
8/10/2017 444 RRR   10 
8/01/2017 144 PR   21 
7/15/2017 12  RRR   10 

下面是該查詢:

select 
q.lastdate, 
r.part, r.location, 
a.agingpolicy as 'Aging Days' 
    from opsintranexcel r (nolock) 
left InventoryAging a (nolock) on r.location=a.location 
left join (select part,MAX(trandate) as lastdate from opsintran group by 
    part) q on r.part=q.part 

這裏是多餘的專欄中,我想補充說:

+---------+------+----------+------------+---------+ 
|LastDate | Part | Location | Aging Days | Age | 
+---------+------+----------+------------+---------+ 
12/1/2016 123  VVV   90  Overage 
8/10/2017 444  RRR   10  Within 
8/01/2017 144  PR   21  Within 
7/15/2017 12  RRR   10  Overage 

我感謝你的幫助。

+0

你在perpost失去了我 – Strawberry

回答

1

我想下面的代碼會爲你

SELECT 
    q.lastdate, 
    r.part, 
    r.location, 
    a.agingpolicy as 'Aging Days' 
    'Age' = 
    CASE 
     WHEN DATEDIFF(day, q.LastDate, GETDATE()) > a.agingpolicy THEN 'Overage' 
     ELSE THEN 'Within' 
    END 
FROM opsintranexcel r (nolock) 
LEFT JOIN InventoryAging a (nolock) on r.location=a.location 
LEFT JOIN (
    SELECT part,MAX(trandate) as lastdate 
    FROM opsintran 
    WHERE trantype='II' and PerPost>='201601' 
    GROUP BY part) q ON r.part=q.part 
+0

謝謝你的工作很好。 – Blackfyre

+0

如果你喜歡,請按下按鈕作爲一個真正的答案:)))))。 –

1

工作,你可以查看當前的日期,如果超過或者內的老化天數

CASE WHEN DATEDIFF(NOW(), q.lastdate) > a.agingpolicy 
    THEN 'Overage' 
    ELSE 'Within' 
END AS age 
-1

您應該修改差和lastdate值您的查詢爲:

select 
q.lastdate, 
r.part, r.location, 
a.agingpolicy as 'Aging Days', 
if(DATEDIFF(NOW(), q.lastdate)) > a.agingpolicy, 'Overage','Within') as 'Age' 
from opsintranexcel r (nolock) 
left InventoryAging a (nolock) on r.location=a.location 
left join (select part,MAX(trandate) as lastdate from opsintran where 
    trantype='II' and PerPost>='201601' group by part) q on r.part=q.part