如何在sql中计数

时间:2015-11-17 16:00:49

标签: sql sql-server

我有两张表如下

| Id |   email |
|----|---------|
|  1 | a@a.com |
|  2 | b@b.com |
|  3 | a@a.com |
|  4 | b@b.com |
|  5 | c@c.com |
|  6 | d@d.com |
|  7 | b@b.com |

-

| Id | names |
|----|-------|
|  1 |  audi |
|  2 |  ford |
|  3 |  ford |
|  4 |  ford |
|  5 |  audi |
|  6 |  benz |
|  7 |   bmw |
|  1 |   bmw |
|  2 |  audi |

现在,我想显示email,count of email and ReqType的列,如果名称表中包含&​​#34;奥迪或福特"那么ReqType列显示为required。别的"Not-Req"

我的查询是:

select  
    email, count(email) as Email,
    case
       when t2.names in ('Audi', 'ford')
          then 'req'
          else 'Not-req'
    end as 'ReqType'
from
    t1
inner join      
    t2 on t1.Id = t2.Id
group by     
    email, names

但它显示为:

|   email | Email | ReqType |
|---------|-------|---------|
| a@a.com |     1 |     req |
| a@a.com |     1 | Not-req |
| a@a.com |     1 |     req |
| b@b.com |     1 |     req |
| b@b.com |     1 | Not-req |
| b@b.com |     2 |     req |
| c@c.com |     1 |     req |
| d@d.com |     1 | Not-req |

必需的输出是

|   email | Email | ReqType |
|---------|-------|---------|
| a@a.com |     2 |     req |
| a@a.com |     1 | Not-req |
| b@b.com |     3 |     req |
| b@b.com |     1 | Not-req |
| c@c.com |     1 |     req |
| d@d.com |     1 | Not-req |

如何实现这一目标?

SqlDemo

2 个答案:

答案 0 :(得分:1)

创建与实际列相同级别的ReqType字段,然后计算。

SELECT
    [email],
    COUNT([email]) AS [Email],
    [ReqType]
FROM
    (
    select          
        email,
        case when t2.names in ('Audi','ford') then 
            'req'
        else
            'Not-req'
        end 
        as 'ReqType'
    from
        t1
        inner join t2 on t1.Id = t2.Id
    ) DerivedWithReqType
GROUP BY
    [email],
    [ReqType]

答案 1 :(得分:1)

@jarlh是对的:

select email,
        count(email) as Email,
        case when t2.names in ('Audi','ford')
                then 'req'
                else 'Not-req'
            end as 'ReqType'
    from t1
      inner join t2 on t1.Id = t2.Id
    group by email, case when t2.names in ('Audi','ford')
                            then 'req'
                            else 'Not-req'
                        end