我有一个类似于以下结构的表:
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
答案 0 :(得分: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);
答案 1 :(得分: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