结合两个选择

时间:2014-09-20 09:40:25

标签: sql sql-server dml

我有下表

测试

+----+---------+------+
| Id | NumFact | type |
+----+---------+------+
| 1  |   20    |  A   |
| 2  |   21    |  A   |
| 3  |   22    |  A   |
| 4  |   23    |  B   |
| 5  |   24    |  B   |
| 6  |   25    |  B   | 
| 7  |   26    |  B   |
| 8  |   26    |  T   |
+----+---------+------+

我需要得到以下结果,只获得A和B的NumFact数

预期结果

+------+--------+
| Num  |   type |
+------+--------+
|  3   |    A   |
|  4   |    B   |
+------+--------+

我写了以下查询

     -- select query 1 --
    Select (count NumFact  )as Num 
    from test 
    where type = 'A' 

     -- select query 2 --
    Select (count NumFact  )as Num 
    from test 
    where type = 'B' 

如何只选择一个选择并获取 Num

4 个答案:

答案 0 :(得分:4)

使用GROUP BY

查询1

SELECT COUNT(NumFact) AS Num,
type FROM test
WHERE type IN ('A','B')
GROUP BY type

QUERY2

SELECT COUNT(NumFact) AS Num,
type FROM test
WHERE type='A' OR type='B'
GROUP BY type;

DEMO

答案 1 :(得分:3)

您只需按type分组并正确过滤。

SELECT type, COUNT(NumFact) AS Num
FROM test
WHERE type IN ('A','B')
GROUP BY type;

这说的是将结果集分组为type列,并为每个组使用汇总函数COUNT(),但仅限于type列值等于'甲'或者' B'。

这真是非常基本的SQL。详细了解GROUP BY on MSDN

答案 2 :(得分:2)

或略有不同的版本:

SELECT COUNT(NumFact) AS Num, Type
FROM test
GROUP BY Type
HAVING (Type = 'A') OR (Type = 'B')

答案 3 :(得分:0)

select 
   type,count(numfact) as num
from  test 
group by type 
order by type

- 或 -

select 
   type,count(numfact) as num 
from  test 
where type in('A','B')
group by type 
order by type