如何在满足多个条件时从表中获取数据

时间:2018-03-20 14:44:11

标签: mysql sql

我有下面提到的表格。

ID    CFE     Val1    Val2
1     123     A       B
2     123     A       C
3     123     A       B
4     456     A       B
5     456     C       B
6     789     C       D

我想获取那些我的CFE值大于1且Val1值为" A" Val2值为" B"或Val1值为任何值(" A"除外),但Val2值为" B"

在一列中,它显示了Count1的计数(Count2 =总计数和CFE =符合条件的地方)。

必需输出:

ID    CFE     Val1    Val2 Count1   Count2
1     123     A       B    3        2
3     123     A       B    3        2
4     456     A       B    2        2
5     456     C       B    2        2

1 个答案:

答案 0 :(得分:1)

这样做

;with src (ID, CFE, Val1, Val2) as
(
    select 1, 123, 'A', 'B' union all
    select 2, 123, 'A', 'C' union all
    select 3, 123, 'A', 'B' union all
    select 4, 456, 'A', 'B' union all
    select 5, 456, 'C', 'B' union all
    select 6, 789, 'C', 'D' 
), ct as
(
    select 
        s.ID,
        s.CFE,
        s.Val1,
        s.Val2,
        count1 = (select count(1)
                  from src i
                  where s.CFE = i.CFE)
    from src s
    where (s.CFE > 1 and s.Val1 = 'A' and s.Val2 = 'B')
        or (s.Val1 != 'A' and s.Val2 = 'B')
)
select 
    Id,
    CFE, 
    Val1,
    Val2,
    Count1,
    Count2 = (select count(1)
              from ct i
              where o.CFE = i.CFE)
from ct o