Group By 时,某列信息只显示最近一条记录的值

highscore2 2015-09-23 09:08:39
商品代码 采购日期 采购数量 采购员
A1 2015-09-01 10 张三
A1 2015-09-10 10 张三
A1 2015-09-13 20 李四
A1 2015-09-20 10 李四

根据月份汇总,商品的采购数量, 并把最新的采购员显示出来
结果如下:

月份 商品 采购数量 最新采购员
2015-09 A1 50 李四
...全文
499 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
哋岼線 2015-09-26
  • 打赏
  • 举报
回复
引用 2 楼 highscore2 的回复:
[quote=引用 楼主 highscore2 的回复:] 商品代码 采购日期 采购数量 采购员 A1 2015-09-01 10 张三 A1 2015-09-10 10 张三 A1 2015-09-13 20 李四 A1 2015-09-20 10 李四 根据月份汇总,商品的采购数量, 并把最新的采购员显示出来 结果如下: 月份 商品 采购数量 最新采购员 2015-09 A1 50 李四
如果是同一日有多次采购就不行了. 类似这种思路我想过了,我再看看有没有其它思路[/quote] 同样的道理,为什么不行,如果是同一天有多次采购最多加个时间作处理..., 楼主需要学以致用
pengxuan 2015-09-26
  • 打赏
  • 举报
回复
如果是同一日有多次采购,你把采购日期加上时间,把记录进入系统的时间做为凭据
pengxuan 2015-09-26
  • 打赏
  • 举报
回复

if OBJECT_ID('tb') is not null
   drop table tb
go
create table tb
(c1 varchar(10),
 c2 datetime,
 c3 int,
 c4 varchar(10)
)
go
insert into tb
select 'A1','2015-09-01',10,'张三' union all
select 'A1','2015-09-10',10,'张三' union all
select 'A1','2015-09-13',20,'李四' union all
select 'A1','2015-09-20',10,'李四'
go
select * from tb a where not exists(select 1 from tb where c1=a.c1 and CONVERT(varchar(6),c2,112)=CONVERT(varchar(6),a.c2,112) and c2>a.c2)
spiritofdragon 2015-09-23
  • 打赏
  • 举报
回复
WITH t(商品代码, 采购日期,采购数量,采购员) AS (
select 'A1','2015-09-01' ,10 , '张三'   union all 
select 'A1','2015-09-10' ,10 , '张三' union all 
select 'A1','2015-09-13' ,20 , '李四' union all 
select 'A1','2015-09-13' ,20 , '李四' union all 
select 'A2','2015-09-20' ,10 ,  '李四'	union all 
select 'A1','2015-08-20' ,10 ,  '李四'	union all 
select 'A2','2015-08-20' ,10 ,  '张三'	
)
,tt as (
select 
	CONVERT(varchar(7),采购日期,120) 采购月份, 商品代码
	,SUM(采购数量)	采购总量 
from t
group by CONVERT(varchar(7),采购日期,120), 商品代码
)
select tt.* ,ttt.采购员
from tt 
cross apply (select top 1 t.采购员 from t where t.商品代码=tt.商品代码 and CONVERT(varchar(7),采购日期,120)=tt.采购月份 order by t.采购日期 desc) ttt
highscore2 2015-09-23
  • 打赏
  • 举报
回复
引用 楼主 highscore2 的回复:
商品代码 采购日期 采购数量 采购员 A1 2015-09-01 10 张三 A1 2015-09-10 10 张三 A1 2015-09-13 20 李四 A1 2015-09-20 10 李四 根据月份汇总,商品的采购数量, 并把最新的采购员显示出来 结果如下: 月份 商品 采购数量 最新采购员 2015-09 A1 50 李四
如果是同一日有多次采购就不行了. 类似这种思路我想过了,我再看看有没有其它思路
Pact_Alice 2015-09-23
  • 打赏
  • 举报
回复
WITH cet AS ( select 'A1' OrderName,'2015-09-01' Dates,10 Number, '张三' Name union all select 'A1', '2015-09-10', 10 , '张三' union all select 'A1' , '2015-09-13' , 20 , '李四' union all select 'A1', '2015-09-20' , 10, '李四' ) SELECT SUBSTRING(cet.dates,1,4)+SUBSTRING(cet.dates,5,3) AS 月份 , cet.OrderName, a.number, cet.Name FROM cet JOIN (SELECT orderName,SUM(number)AS number,MAX(dates)dates FROM cet GROUP BY ordername)a ON a.ordername=cet.ordername AND a.dates=cet.dates

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧