2017-04-02 72 views
0

我有一個表像下面的結構:如何做一個查詢的選擇上組的一些選擇DATAS

ID|PrcessorID|BatchNO|NoOfTransaction|BatchCreatedDate 
1 |20  |2  |3    |2017-03-28 
2 |21  |3  |3    |2017-04-01 
3 |21  |4  |7    |2017-04-01 
4 |20  |5  |3    |2017-04-01 
5 |21  |6  |2    |2017-04-02 
6 |20  |7  |4    |2017-04-02 

,另一個表就像

ProcessorID|ProcessorName 
20   |Payme 
21   |Payany 

我一定要得到的數據總無交易和一批由3天前組的每個特定的處理器每個特定日期的數量由處理器,使我能得到這樣的數據:

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate 

    Payany |2   |10    |2017-04-01 
    Payme |1   |3     |2017-04-01 
    Payany |1   |2     |2017-04-02 
     Payme |1   |4     |2017-04-02 

什麼,我的樂隊現在的問題是:

Select a.ProcessorId As ProcessorID,b.ProcessorName As ProcessorName,BatchCreatedDate,Sum(NoofTRansaction) As TotNoofTransaction,Count(BatchNo) As BatchCountfrom TableA a innerjoin TableB b on a.ProcessorID=b.ProcessorID where BatchcreatedDate<GetDate() and BatchCreatedDate>GetDate()-4 groupby ProcessorName,BatchCreatedDate 

但此查詢是給我造成像

PrcessorName|Batchcount|TotNoOfTransaction|BatchCreatedDate 

    Payany |1   |3     |2017-04-01 
    Payany |1   |7     |2017-04-01 
    Payme |1   |3     |2017-04-01 
    Payany |1   |2     |2017-04-02 
     Payme |1   |4     |2017-04-02 

回答

1

我最好的猜測是,BatchCreatedDate具有時間分量。這是否做你想要的?

Select a.ProcessorId As ProcessorID, b.ProcessorName As ProcessorName, 
     cast(BatchCreatedDate as date) as bcd, 
     Sum(NoofTRansaction) As TotNoofTransaction, 
     Count(BatchNo) As BatchCount 
from TableA a inner join 
    TableB b 
    on a.ProcessorID = b.ProcessorID 
where BatchcreatedDate < GetDate() and BatchCreatedDate > GetDate()-4 
group by a.ProcessorId, b.ProcessorName, cast(BatchCreatedDate as date); 
+0

是它的時間字段 – Tanmay

1
;WITH Cte1 (ID,ProcessorID,BatchNO,NoOfTransaction,BatchCreatedDate) 
As 
(
SELECT 1 ,20 ,2 ,3 ,'2017-03-28' UNION ALL 
SELECT 2 ,21 ,3 ,3 ,'2017-04-01' UNION ALL 
SELECT 3 ,21 ,4 ,7 ,'2017-04-01' UNION ALL 
SELECT 4 ,20 ,5 ,3 ,'2017-04-01' UNION ALL 
SELECT 5 ,21 ,6 ,2 ,'2017-04-02' UNION ALL 
SELECT 6 ,20 ,7 ,4 ,'2017-04-02' 
) 
,cte2(ProcessorID,ProcessorName) AS (
     SELECT 20,'Payme'UNION ALL 
     SELECT 21,'Payany' 
     ) 

SELECT DISTINCT cte2.ProcessorName 
    ,COUNT(BatchNO) OVER (
     PARTITION BY cte1.ProcessorID 
     ,Cte1.BatchCreatedDate ORDER BY Cte1.BatchCreatedDate 
     )As Batchcount 
    ,SUM(NoOfTransaction) OVER (
     PARTITION BY Cte1.ProcessorID 
     ,Cte1.BatchCreatedDate ORDER BY Cte1.BatchCreatedDate 
     ) As TotNoOfTransaction 
    ,cte1.BatchCreatedDate 
FROM Cte1 
INNER JOIN cte2 ON cte2.ProcessorID = Cte1.ProcessorID 
ORDER BY cte1.BatchCreatedDate