作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个如下例所示的支付表,我需要一个查询,以提供支付了多少个 ID (AMOUNT > 0) 1 次、2 次、3 次或更多次。示例:
+----+--------+
| ID | AMOUNT |
+----+--------+
| 1 | 50 |
| 1 | 0 |
| 2 | 10 |
| 2 | 20 |
| 2 | 15 |
| 2 | 10 |
| 3 | 80 |
+----+--------+
我期待结果:
+-----------+------------+-------------+
| 1 payment | 2 payments | 3+ payments |
+-----------+------------+-------------+
| 2 | 0 | 1 |
+-----------+------------+-------------+
ID 1:支付 1 次 (50)。另一笔付款是0,所以没算。因此,1 人支付 1 次。
ID 2:支付了 3 次 (10,20,15)。因此,1 人支付了 3 次或更多次。
ID 3:支付 1 次 (80)。因此,2 人支付 1 次。
我现在正在 excel 上手动操作,但我很确定有更实用的解决方案。有什么想法吗?
最佳答案
一个小的子查询就可以了
Declare @YOurTable table (ID int, AMOUNT int)
Insert into @YourTable values
( 1 , 50 ),
( 1 , 0) ,
( 2 , 10) ,
( 2 , 20) ,
( 2 , 15) ,
( 2 , 10) ,
( 3 , 80)
Select [1_Payment] = sum(case when Cnt=1 then 1 else 0 end)
,[2_Payment] = sum(case when Cnt=2 then 1 else 0 end)
,[3_Payment] = sum(case when Cnt>2 then 1 else 0 end)
From (
Select id
,Cnt=count(*)
From @YourTable
Where Amount<>0
Group By ID
) A
返回
1_Payment 2_Payment 3_Payment
2 0 1
关于sql - 按 1、2 或 3+ 计算谁付了钱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39661814/
我是一名优秀的程序员,十分优秀!