问题时的SQL案例

时间:2017-08-17 23:22:44

标签: mysql sql

我正在尝试将交易日期排序为老化策略。当LastDate位于超出Aging Days限制政策的位置时,如果OverAge没有引用当前日期,则应显示为Within。 这是当前的表格:

+---------+------+----------+-------------+
|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

感谢您的帮助。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

如果超过或在老化天数内,您可以检查当前日期和最后日期值的差异

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

答案 2 :(得分:-1)

您应该将查询修改为:

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