繁体   English   中英

选择多列计算一列并在一张表中按一列分组

[英]select multiple columns count one column and group by one column in one table

我有一个名为[delivery]的表,其[ID],[Employee],[Post],[c_name],[Deli_Date],[note]

我需要选择所有列并计算Employee ,然后按Employee分组。 表格中的数据如下所示:

  ---------------------------------------------------
  | Employee| Post      |c_name  |Deli_Date   |Note |
  |---------|-----------|---------------------|-----|
  |  DAVID  |MANAGER    | a      |11/11/2018  |note |
  |  DAVID  |MANAGER    | b      |01/01/2015  |note |
  |  SAM    |ACOUNTS    | c      |10/10/2016  |note |
  |  DAVID  |IT         | a      |10/02/2015  |note |
  |  DAVID  |DOCTOR     | c      |20/02/2017  |note |
  |  JAMES  |DELIVERYMAN| b      |05/05/2015  |note |
  |  OLIVER |DRIVER     | b      |02/02/2014  |note |
  |  SAM    |ACOUNTS    | c      |02/02/2012  |note |

此代码:

select Employee, count(Employee) as TIMES from delivery
group by Employee

结果是:(但是我也需要显示其他列)。

| Employee| TIMES | 
|---------|-------|
|  DAVID  |   4   |
|  JAMES  |   1   |
|  OLIVER |   1   |
|  SAM    |   2   |

我需要这样的代码显示:

| Employee| TIMES | Post      |c_name  |Deli_Date   |Note |
|---------|-------|-----------|---------------------|-----|
|  DAVID  |   4   |MANAGER    | a      |11/11/2018  |note |
|  JAMES  |   1   |DELIVERYMAN| b      |05/05/2015  |note |
|  OLIVER |   1   |DRIVER     | b      |02/02/2014  |note |
|  SAM    |   2   |ACOUNTS    | c      |10/10/2016  |note |

什么是最好的查询可以给我那个结果?

参见[c_name],[Deli_Date][c_name],[Deli_Date]它们显示了最后插入的数据。 或者只给我没有[c_name],[Deli_Date]的结果就可以了。

如果需要最后一个日期和计数,则可以使用窗口功能:

select d.Employee, d.cnt, d.Post, d.c_name, d.Deli_Date, d.Note 
from (select d.*,
             count(*) over (partition by employee) as cnt,
             row_number() over (partition by employee order by deli_date desc) as seqnum
      from delivery d
     ) d
where seqnum = 1;
select Employee, count(Employee) as TIMES,Post,c_name,Deli_Date,Note from delivery
group by Employee

您需要在select和group by子句中包括所有未聚合的列

select Employee,
  count(Employee) as TIMES,
  max(Deli_date) as LAST_DELI_DATE,
  post,
  note
from delivery
group by Employee, post, note

Max(Deli_date)将为您提供最新日期。

要获取最新的c_name,注释,帖子等,您将需要一个带有按deli_date排序的rank函数的子查询。 稍后将添加示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM