T -Sql查询尝试仅选择包含两个寄存器编号的商店编号

时间:2016-11-15 16:06:21

标签: sql tsql

我现在有一个查询我想只选择只包含52,53的store_numbers如果它只包含一个或另一个,那么任何人都可以帮助

DECLARE @Date_value date; 
SET @Date_value = (SELECT MAX(REPORT_DATE) FROM sco_levels WHERE register_nbr BETWEEN 52 AND 54)


 SELECT STORE_NBR, REGISTER_NBR, MAX(report_date), CASE When MAX(report_date) <> GETDATE() -1 THEN DateDiff(day, max(report_date), @Date_value) else 0 end as DiffDate
from sco_levels
where register_nbr between 52 and 53
AND  report_date <> GetDate() -1
group by store_nbr, register_nbr
order by store_nbr, register_nbr

1 个答案:

答案 0 :(得分:0)

这是一种方式

select STORE_NBR
from sco_levels
Where register_nbr in (52,53)
Group by STORE_NBR
Having count(distinct register_nbr) = 2

您可以将以上查询添加到您的查询中,以过滤同时包含STORE_NBR52

53
SELECT store_nbr, 
       register_nbr, 
       Max(report_date), 
       CASE 
         WHEN Max(report_date) <> Getdate() - 1 THEN 
         Datediff(day, Max(report_date), @Date_value) 
         ELSE 0 
       END AS DiffDate 
FROM   sco_levels s1 
WHERE  register_nbr BETWEEN 52 AND 53 
       AND report_date <> Getdate() - 1 
       AND EXISTS (SELECT 1 
                   FROM   sco_levels s2 
                   WHERE  s2.register_nbr IN ( 52, 53 ) 
                          AND s1.store_nbr = s2.store_nbr 
                   HAVING Count(DISTINCT s2.register_nbr) = 2) 
GROUP  BY store_nbr, 
          register_nbr 
Having Datediff(day, Max(report_date), @Date_value) > 7
ORDER  BY store_nbr, 
          register_nbr