如何实现这个输出?

Mar1009

我有一个包含如下数据的表:

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
萨尔曼

你的逻辑有点正确,你只需要把CASE表达式放在里面COUNT,而不是相反:

SELECT customerNumber
     , COUNT(*) AS TotalTxns
     , COUNT(CASE WHEN txnstatus = 1 THEN 1 END) AS SuccessFulTxns
     , COUNT(CASE WHEN txnstatus = 2 THEN 1 END) AS FailedTxns
FROM test
GROUP BY customerNumber

请注意,没有空 INT 之类的东西。转换为 INT 时,空字符串/空格变为 0。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章