具有不同条件的多个计数

时间:2014-03-15 21:33:13

标签: sql sql-server count

我想在一行中检索并显示员工的销售数量,然后是销售总数。

SELECT COUNT(SalesID) AS SalesForEmployee, COUNT(SalesID) AS TotalSales
FROM Sales
WHERE EmployeeID = 123

如何使where子句仅适用于select?

中的第一列

4 个答案:

答案 0 :(得分:0)

您不能拥有仅适用于一列的where

为了在只扫描一次表时获得两个计数,您可以这样做:

select 
    sum(case when EmployeeID=123 then 1 else 0 end) as SalesForEmployee, 
    Count(SalesID) as TotalSales
from Sales

没有where条款,因为Count(SalesID)需要计算每一行以计算总数。

由于您必须查看每一行,case when EmployeeID=123 then 1 else 0 end为每个属于目标员工的行提供1,为每行不提供0 。因此,总结该表达式只会为该员工提供计数。

SalesID     EmployeeID (case when ... )
1           123         1
2           311         0
3           333         0
4           123         1
5           300         0
count = 5               sum = 2

你也可以这样做:

select
    (select count(SalesID) from Sales where EmployeeID=123) as SalesForEmployee,
    (select count(SalesID) from Sales) as TotalSales

但是现在你要扫描Sales表两次,这会慢一些。

答案 1 :(得分:0)

SELECT 
  sum(case when EmployeeID = 123 then 1 else 0 end) AS SalesForEmployee
 ,COUNT(SalesID) AS TotalSales
FROM Sales

答案 2 :(得分:0)

select count(SalesEmp.SalesID) AS SalesForEmployee count(Sales.salesID) As TotalSales 
from Sales left outer join Sales as SalesEmp
on Sales.salesID=SalesEmp.SalesID
and SalesEmp.EmployeeID = 123

答案 3 :(得分:0)

这是一个嵌套的子查询方法,将两个select语句合并为一个。

SELECT 
    (SELECT COUNT(SalesID) FROM Sales WHERE EmployeeID = 123) AS SalesForEmployee, 
    (SELECT COUNT(SalesID) FROM Sales) AS TotalSales

另一种写它的方式就是这样。

SELECT COUNT(SalesID) AS SalesForEmployee, 
    (SELECT COUNT(SalesID) FROM Sales) AS TotalSales
FROM Sales WHERE EmployeeID = 123

使用相关子查询,您可以将外部查询与内部查询链接。假设您希望获得的总销售额不包括EmployeeID 123的销售额

SELECT COUNT(SalesEmployee.SalesID) AS SalesForEmployee, 
    (SELECT COUNT(SalesID) FROM Sales WHERE Sales.EmplyeeID <> SalesEmployee.EmployeeID) AS TotalSales
FROM Sales As SalesEmployee WHERE SalesEmployee.EmployeeID = 123

这里内部查询引用WHERE子句中的outeeeries EmployeeeID来过滤它们。