2016年2月只有存款且没有提款的帐户脚本

时间:2016-02-29 00:46:28

标签: sql sql-server

我在SQL中使用我的脚本进行了新手,因为我需要的是在二月份才能让帐户只有存款且没有提取,但是我无法想到一个可以获得我需要的查询的脚本,尝试一个独特的,分组,但不显示我需要的东西:

表格顺序:

CuentasBancaria

cuentasbancaria

Retiros /取款

enter image description here

Depositos /存款

enter image description here

我试过这个脚本:

DECLARE @FechaDeterminado VARCHAR(10)
SET @FechaDeterminado = '2016-02-01'

IF EXISTS(SELECT a.FechaMovimiento FROM [dbo].[Retiros] a 
                    INNER JOIN [dbo].[CuentasBancarias] b
                    ON a.CuentaId = b.CuentaId 
                    WHERE a.FechaMovimiento >= @FechaDeterminado)
BEGIN
    RAISERROR('No hay clientes sin retiros en el mes',16,1)
END

IF NOT EXISTS(SELECT a.FechaMovimiento FROM [dbo].[Retiros] a 
                    INNER JOIN [dbo].[CuentasBancarias] b
                    ON a.CuentaId = b.CuentaId 
                    WHERE a.FechaMovimiento >= @FechaDeterminado)
BEGIN 
        SELECT * FROM [dbo].[CuentasBancarias] a
        INNER JOIN [dbo].[Depositos] b
        ON a.CuentaId = b.CuentaId 
        WHERE FechaMovimiento >= @FechaDeterminado
END 

但它不正确...因为它显示了没有提款时的结果,但是至少在撤退时显示失败,我想要的是实现一个脚本或查询以获得那些只做过拒绝的客户本月存款和取款

1 个答案:

答案 0 :(得分:1)

您不需要if。您可以使用WHERE子句执行此操作:

select cb.*
from CuentasBancaria cb
where not exists (select 1
                  from retiros r
                  where cb.CuentaId = r.CuentaId and
                        r.FechaMovimiento >= '2016-02-01' and
                        r.FechaMovimiento < '2016-03-01' 
                 ) and
      exists (select 1
              from depositors d
              where cb.CuentaId = d.CuentaId and
                    d.FechaMovimiento >= '2016-02-01' and
                    d.FechaMovimiento < '2016-03-01' 
             );