仅过滤ON子查询

时间:2014-02-27 05:33:17

标签: sql sql-server

我有一个返回四列的查询,我想将日期范围/过滤器仅应用于两个列,之前我写了我的查询,如下所示。

SELECT TOP (100) PERCENT dbo.Collector.name, 
       dbo.Debtor.batchno AS batchno, 
       COUNT(dbo.Debtor.id) AS cases, 
       SUM(dbo.Debtor.totalDebt) AS amount, 
       SUM(dbo.Payment.payment) AS collection,
       SUM(dbo.Debtor.balance) AS OSBalance, 
       dbo.debtor.receivedDate    
  FROM dbo.Payment WITH (NOLOCK) 
       INNER JOIN dbo.Collector WITH (NOLOCK) 
             ON dbo.Payment.collectorid = dbo.Collector.id 
       INNER JOIN dbo.Debtor WITH (NOLOCK) 
             ON dbo.Payment.debtorid = dbo.Debtor.id 
       INNER JOIN dbo.Client WITH (NOLOCK) 
             ON dbo.debtor.clientid = dbo.Client.id   
 WHERE dbo.Payment.paymentdate BETWEEN ' 2011-02-27 00:00:00.000 ' 
                                   AND  '2014-02-27 23:59:59.000'     
       AND dbo.Payment.confirmed='Y' 
GROUP BY  
       dbo.Collector.name, 
       dbo.Debtor.batchno,
       dbo.debtor.receivedDate 
ORDER BY 
       dbo.debtor.receivedDate DESC

以上按付款日期过滤所有列。但是我希望按付款日期过滤仅适用于两个列,例如case和collecton,如下所示。

SELECT TOP (100) PERCENT dbo.Collector.name, 
       dbo.Debtor.batchno AS batchno,
       (
   SELECT COUNT(dbo.Debtor.id) 
   FROM dbo.Debtor d INNER JOIN dbo.Payment p ON d.id = p.debtorid
   WHERE paymentdate BETWEEN ' 2011-02-27 00:00:00.000 ' 
                          AND  '2014-02-27 23:59:59.000' 
          AND batchno=dbo.Debtor.batchno 
           AND dbo.collector.name= dbo.collector.name
   ) AS cases, 
       SUM(dbo.Debtor.totalDebt) AS amount, 
       (
        SELECT SUM(dbo.Payment.payment) 
         FROM dbo.Payment 
        WHERE paymentdate BETWEEN ' 2011-02-27 00:00:00.000 ' 
                              AND  '2014-02-27 23:59:59.000' 
              AND batchno= dbo.Debtor.batchno 
              AND name= dbo.collector.name
         ) AS collection,
       SUM(dbo.Debtor.balance) AS OSBalance, 
       dbo.debtor.receivedDate    
  FROM dbo.Payment WITH (NOLOCK) 
       INNER JOIN dbo.Collector WITH (NOLOCK) 
             ON dbo.Payment.collectorid = dbo.Collector.id 
       INNER JOIN dbo.Debtor WITH (NOLOCK) 
             ON dbo.Payment.debtorid = dbo.Debtor.id 
       INNER JOIN dbo.Client WITH (NOLOCK) 
             ON dbo.debtor.clientid = dbo.Client.id   
 WHERE dbo.Payment.confirmed='Y' 
GROUP BY 
       dbo.Collector.name, 
       dbo.Debtor.batchno,
       dbo.debtor.receivedDate 
ORDER BY 
       dbo.debtor.receivedDate DESC

以上对我不起作用。此外,我想只通过batchno和名称分组。此外,集合和案例列必须按付款日期过滤。请问我该如何实现这一目标?任何帮助,将不胜感激。最热烈的关注

0 个答案:

没有答案