当其中一个结果未通过测试时,如何删除与分组ID相关的所有结果

时间:2018-05-04 19:30:39

标签: sql sql-server ibm-midrange

所以我要做的是从KEYVADD(ID)分组的CKDBAUDDP中检索所有订单。我当时想要做的只是在状态在特定日期范围内时才返回订单。使用我目前拥有的代码,使用STMPADD比较添加另一个“和”只会从已完成的查询中删除这些结果。这不是我想要发生的事情,因为结果变得不那么明确了。

exec('  select KEYVADD
    ,min(case when VALUADD=0 then STMPADD else null end) as "Status 0"
    ,min(case when VALUADD=2 then STMPADD else null end) as "Status 2"
    ,min(case when VALUADD=4 then STMPADD else null end) as "Status 4"
    ,min(case when VALUADD=5 then STMPADD else null end) as "Status 5"
    ,min(case when VALUADD=7 then STMPADD else null end) as "Status 7"
    ,min(case when VALUADD=8 then STMPADD else null end) as "Status 8"
    ,min(case when VALUADD=9 then STMPADD else null end) as "Status 9"
    ,min(nmdoh) as "Customer"
    ,min(c.scscn) as "Container"
    ,min(whsoh) as "Warehouse"
    ,min(preoh) as "Preorder"
from CKDBAUDDP a
left outer join mvpscohp h on left(a.KEYVADD,7) = h.ONHOH
left outer join mvpscnhp c on h.onhoh = c.onhcn
where whsoh in (700,711,721,731) 
    and IMGTADD = ''A''
    and KEYVADD IN (786398200,786417600)                                                                                                     
group by KEYVADD

') at nordic

以下是从上面的查询中检索到的一些测试数据。

KEYVADD    |            Status 0            |           Status 2            |           Status 4            |   Status 5  | Status 7  |             Status 8         |  Status 9  |     Customer  | Container  |    Warehouse | Preorder
786398200  |  2018-04-30 13:07:53.8780000   |   2018-04-30 10:21:41.9330000 |  2018-04-30 13:08:18.8560000  |   NULL      | NULL      | 2018-04-30 16:33:11.8850000  |  NULL      |  test name    |  27739742  |      721     |  N
786417600  |  2018-04-30 13:07:53.9080000   |   2018-04-30 11:21:15.7810000 |  2018-04-30 13:08:18.8930000  |   NULL      | NULL      | 2018-04-30 18:13:07.7940000  |  NULL      |  test name 2  |  27739744  |      721     |  N

问题出在这个例子中,如果我不希望第二个出现,因为状态2是在上午11点之后,我把它放在And语句中,它只是删除时间并将Null放入结果不是我想要的。如何将它一起删除该ID?

对不起,这是太多的信息,但希望它清楚我想要得到的东西。谢谢!

1 个答案:

答案 0 :(得分:3)

我想你会使用having

having datepart(hour, min(case when VALUADD = 2 then STMPADD end)) >= 11