如果超过2/3满足值,则返回所有记录

时间:2015-07-24 07:16:46

标签: sql sql-server-2008

我有一张表,表示客户在任何一天内的多笔交易。如果每个客户的三分之二或更多交易是现金而不是信用卡,我需要返回每个客户的所有交易。

在下面的示例中,我想要归还所有客户' 1,4次交易,因为他们是唯一拥有三分之二或更多交易作为现金的客户:

+----------------+-------------+-----------------+------------------+
| Transaction ID | CustomerNum | TransactionType | TransactionValue |
+----------------+-------------+-----------------+------------------+
|              1 |           1 | Cash            |               11 |
|              2 |           1 | Card            |               12 |
|              3 |           1 | Cash            |               13 |
|              4 |           2 | Cash            |               14 |
|              5 |           2 | Card            |               15 |
|              6 |           3 | Cash            |               15 |
|              7 |           3 | Card            |               11 |
|              8 |           3 | Cash            |               12 |
|              9 |           3 | Card            |               13 |
|             10 |           4 | Cash            |               14 |
|             11 |           4 | Cash            |               15 |
|             12 |           4 | Cash            |               15 |
+----------------+-------------+-----------------+------------------+

2 个答案:

答案 0 :(得分:4)

这似乎适用于样本数据:

declare @t table (TranID int not null,CustomerNum int not null,
                  TranType varchar(17) not null,TranValue decimal(18,0) not null)
insert into @t(TranID,CustomerNum,TranType,TranValue) values
( 1,1,'Cash',11),    ( 2,1,'Card',12),    ( 3,1,'Cash',13),
( 4,2,'Cash',14),    ( 5,2,'Card',15),
( 6,3,'Cash',15),    ( 7,3,'Card',11),    ( 8,3,'Cash',12),    ( 9,3,'Card',13),
(10,4,'Cash',14),    (11,4,'Cash',15),    (12,4,'Cash',15)

;With Counted as (
    select *,
        COUNT(*) OVER (PARTITION BY CustomerNum) as cnt,
        SUM(CASE WHEN TranType='Cash' THEN 1 ELSE 0 END)
            OVER (PARTITION BY CustomerNum) as cashcnt
    from @t
)
select * from Counted
where cashcnt * 3 >= cnt * 2

我在最后使用简单乘法将所有数学保持为整数,并避免考虑浮点数/小数和2/3的表示。

结果:

TranID      CustomerNum TranType          TranValue   cnt         cashcnt
----------- ----------- ----------------- ----------- ----------- -----------
1           1           Cash              11          3           2
2           1           Card              12          3           2
3           1           Cash              13          3           2
10          4           Cash              14          3           3
11          4           Cash              15          3           3
12          4           Cash              15          3           3

答案 1 :(得分:0)

试试这个:

select t.*
from (select customernum
      from transactions
      group by customernum
      having sum(case when TransactionType = 'Cash' then 1.0 else 0.0 end) / sum(1.0) > 0.6666) c
join transactions t on t.customernum = c.customernum