计算单独字段中具有匹配值的记录数

时间:2017-02-06 13:08:55

标签: sql sql-server-2008 count

数据库/ SQL新手在这里。 我在DB MS SQL Server 2008中有一个表,如下所示:

number of request,      employee,   parameter1, parameter2, parameter3
ID1139151   employee1   1   1   0
ID1139152   employee1   0   0   1
ID1139153   employee1   0   1   0
ID1139154   employee2   0   0   1
ID1139155   employee2   0   1   1
ID1139156   employee2   1   1   0
ID1139157   employee3   0   1   0
ID1139158   employee3   0   1   0

我想通过值parameter1,parameter2,parameter3,请求数

找到行数

结果应该是这样的:

SUMM number of request,     employee,   SUMM parameter1,    SUMM parameter2,    SUMM parameter3
3   employee1   1   2   1
3   employee2   1   2   2
2   employee3   0   2   0

我该怎么办?请帮帮我。

2 个答案:

答案 0 :(得分:3)

当你开始使用SQL时,你会意识到 - 当然对于更简单的查询 - 你基本上是用英语编写非常简单的句子,只缺少一些单词。

如果您考虑英语声明:

I want to select this column and that column from this table where that column's value is 1

你可以这样格式化:

I want to:
select this column
       and that column
from this table
where that column's value = 1

你可能会看到这将进入纯SQL:

select ThisColumn
      ,ThatColumn
from ThisTable
where ThatColumn = 1

然后,您可以通过添加聚合来使其更加复杂,这些聚合分组在某些列中:

I want to:
select this column
       and count all the rows that are returned
       and add up all the values in that column
from this table
grouped by the different values in this column

在SQL中看起来像:

select ThisColumn
      ,count(ThatColumn) as ThatColumnCount
      ,sum(ThatColumn) as ThatColumnTotal
from ThisTable
group by ThisColumn

如果您能理解上述内容,那么您应该能够编写自己的脚本而不会出现太多问题。当然,没有谷歌在你进入更复杂的东西之前无法解决这些问题。

答案 1 :(得分:2)

select count([number of request],
       employee,
       sum(parameter1) as sum_p1,
       sum(parameter2) as sum_p2,
       sum(parameter3) as sum_p3
from your_table
group by employee