Sat*_*mar 0 sql-server cte group-by
这是 SQL Server CTE,
;with grp (Sdate,TransactionType,tot)
as
(select cast(CallStartTime as DATE)Date, Transaction_type as [Transaction type],
(count ([Transaction_type])) as [Total Count]
from TBL_AGENT_TRANSACTIONS
where cast(CallStartTime as DATE)>='2015-04-27' and cast(CallEndTime as Date)<='2015-04-27' and Transaction_type in ('Debit_Card')
group by CallStartTime, Transaction_type)
select grp.Sdate,grp.TransactionType,sum(grp.tot) as totalCount from grp group by TransactionType,grp.Sdate,grp.tot
Run Code Online (Sandbox Code Playgroud)
这里我想根据 Sdate 和 Transaction Type 对 totalcount 进行分组。但它不能正常工作。我有 3 条具有相同 Sdate、Transaction Type 的记录,我需要将 totalcount 显示为 3 作为一行。但我得到如下两行。
任何人都可以帮我解决这个小问题吗?
更新:
我得到了确切的问题,
在我的表“ TBL_AGENT_TRANSACTIONS ”中,列“ Transaction_type ”的数据类型是 varchar 但我需要根据 Sdate 和 Transaction_type 找到该 Transaction_type 的总和。如果我sum(Transaction_type)
输入第一个选择查询,它会显示数据类型转换失败错误,所以我count(Transaction_type)
在第一个选择查询中找到并在第二个选择查询中获取该字段的总和。我想我的问题只在这个过程中。
在您的 GROUP BY 中添加 cast(CallStartTime as DATE):
;with grp (Sdate,TransactionType,tot)
as
(select cast(CallStartTime as DATE)Date, Transaction_type as [Transaction type],
(count ([Transaction_type])) as [Total Count]
from TBL_AGENT_TRANSACTIONS
where cast(CallStartTime as DATE)>='2015-04-27'
and cast(CallEndTime as Date)<='2015-04-27'
and Transaction_type in ('Debit_Card')
group by cast(CallStartTime as DATE), Transaction_type)
select grp.Sdate,grp.TransactionType,sum(grp.tot) as totalCount
from grp
group by TransactionType,grp.Sdate,grp.tot
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9988 次 |
最近记录: |