【发布时间】:2019-09-02 02:07:56
【问题描述】:
我有一张这样的数据表:
create table test (transferID int, customerNumber varchar(10), txnstatus int);
insert into test
values
(1, 1001, 1),
(2, 1001, 2),
(3, 1001, 1),
(4, 1002, 2),
(5, 1002, 1),
(6, 1002, 2),
(7, 1002, 1),
(8, 1002, 1),
(9, 1003, 2),
(10, 1003, 1),
(11, 1003, 1),
(12, 1003, 1),
(13, 1003, 1),
(14, ' ', 1),
(15, ' ', 2),
(16, NULL, 2);
例外的输出是显示客户编号、每个客户的交易总数、成功交易、失败交易的字段。请注意:
- txnStatus 1 和 2 分别代表“成功”和“失败”。
- 在某些情况下,例如最后三行,客户编号可能为空或为 NULL
这是我尝试的方法,但没有得到异常结果
select customerNumber,
count(*) over (partition by 1) as TotalTxns,
case when txnstatus = 1 then count(txnstatus) else 0 end as successFulTrxn,
case when txnstatus = 2 then count(txnstatus) else 0 end as failedFulTrxn
from test
group by customerNumber, txnstatus
我希望输出是:
CustNumber TotalTxns SuccessFulTxns FailedTxns
1001 3 2 1
1002 5 3 2
1003 5 4 1
2 1 1
NULL 1 0 1
【问题讨论】:
-
没有空的
int。它是null或一个数字。和字符串不一样。 -
supplyinf DDL 和 DML 做得很好,但测试它也很重要。那句话是行不通的;无效。
标签: sql sql-server tsql group-by aggregate-functions