我有如下表格
SCHEME BROKNO BRANNO ACCNO TYPE SCAMT FUNAMT MONTH
AFS 123 345 125635 RN 130 140 11
AFS 123 345 125635 RN 130 140 11
AFS 123 345 125635 RN 145 185 11
AFS 123 345 125635 RN 130 140 11
AFS 123 345 125635 RN 180 220 10
AFS 123 345 125635 RN 200 260 10
AFS 123 345 125635 RN 180 220 10
AFS 123 345 125635 RN 180 220 10
现在我必须根据月份列创建报告并基于组(SCHEME,BROKNO,BRANNO,ACCNO,TYPE)。
报告应该是
SCHEME BROKNO BRANNO ACCNO TYPE SUM(SCAMT) SUM(FUNAMT) MONTH11CNT
AFS 123 345 125635 RN 535 605 4
SUM(SCAMT) SUM(FUNAMT) MONTH11CNT
740 920 4
我已尝试使用case语句,但我对所有记录组都有相同的计数。请有人给我一点想法。
答案 0 :(得分:1)
看起来你只想按照计划,brokno,branno,accno,类型和月份进行分组:
select
scheme, brokno, branno, accno, type, month,
sum(scamt), sum(funamt), count(*) as monthcnt
from mytable
group by scheme, brokno, branno, accno, type, month;
编辑:如果要在列中显示月份,您必须事先知道几个月并相应地编写查询:
select
scheme, brokno, branno, accno, type,
sum(case when month = 10 then scamt end) as month10scamt,
sum(case when month = 10 then funamt end) as month10funamt,
sum(case when month = 10 then 1 end) as month10cnt,
sum(case when month = 11 then scamt end) as month11scamt,
sum(case when month = 11 then funamt end) as month11funamt,
sum(case when month = 11 then 1 end) as month11cnt
from mytable
where month in (10,11)
group by scheme, brokno, branno, accno, type;
答案 1 :(得分:0)
您可以使用它来获得您想要的结果
SELECT
SCHEME,
BROKNO,
BRANNO,
ACCNO,
TYPE,
SUM(SCAMT) As SCAMTTOTAL,
SUM(FUNAMT) AS FUNAMTTOTAL,
MONTH As MONTHNAME,
COUNT(MONTH) AS MONTHCOUNT
FROM MyTABLE
GROUP BY
SCHEME,
BROKNO,
BRANNO,
ACCNO,
TYPE,
MONTH
如果您需要将结果放在一行中,那么只需将其转换为CTE并查询即可。
答案 2 :(得分:0)
假设您想要计算每个月内的行数,一个解决方案是将月份纳入聚合:
select SCHEME, BROKNO, BRANNO, ACCNO, TYPE, MONTH,
sum(SCAMT),
sum(FUNAMT),
Count(*) as MONTHCOUNT
from table
group by SCHEME, BROKNO, BRANNO, ACCNO, TYPE, MONTH