Sql Select语句具有不同的where语句

时间:2014-12-10 11:41:26

标签: sql

我正在尝试创建一个select count语句,其中where语句对于每一行都不同 例如,我得到了下表dbo.job:

User:    Job:
Mark     Garbageman
Dirk     Garbageman
Henk     Garbageman
Steven   Garbageman
Mark     Delivery
Dirk     Delivery
Henk     Delivery
Steven   Delivery
Stevens  Delivery

现在我想知道我在垃圾箱的工作中有多少用户“工作”,为此我使用:

Select COUNT(user) as count from job WHERE job.job = 'Garbageman' 

我会得到以下结果:

Count:
4

现在我也想知道有多少用户在同一个选择语句中完成了交付工作,我会得到类似的信息:

Select COUNT(user) as GarbageCount, COUNT(user) as Deliverycount from job WHERE job.job = 'Garbageman' 

现在我将得到以下结果:

GarbageCount:   DelivryCount:
4               4

但我想:

现在我将得到以下结果:

GarbageCount:   DelivryCount:
4               5

我知道为什么我的陈述失败了,那是因为我只使用1 where语句。但是GarbageCount和DeliveryCount的where语句是不同的。我根本不知道如何创建这样的查询。

有人有什么建议吗?

3 个答案:

答案 0 :(得分:1)

你可以使用Case When with Count。

http://peoplesoft.wikidot.com/conditional-counting-in-sql
MSDN参考 - > http://msdn.microsoft.com/en-us/library/ms175997.aspx

select
    count(case when Job = 'Garbageman' then 1 end) as GarbageCount,
    count(case when Job = 'Delivery' then 1 end) as DeliveryCount
from Job

答案 1 :(得分:0)

您可以使用条件sum()

来实现此目的
select
sum(Job = 'Garbageman') as GarbageCount,
sum(Job = 'Delivery') as DelivryCount
from job

答案 2 :(得分:0)

您可以使用条件聚合。 ANSI标准方法是:

Select sum(case when j.job = 'Garbageman' then 1 else 0 end) as GarbageCount,
       sum(case when j.job = 'Delivery' then 1 else 0 end) as Deliverycount
from job j;

您没有指定数据库,但MySQL也提供了以下快捷方式:

Select sum(j.job = 'Garbageman') as GarbageCount,
       sum(j.job = 'Delivery') as Deliverycount
from job j;