是否知道如何使用列显示用户休假的最小到最大日期的输出?
LeaveMain
User | RequestNo
user1 | 123456
LeaveDetail
RequestNo | Date
123456 | 01/01/2017
123456 | 01/02/2017
123456 | 01/03/2017
期望输出
RequestNo | User | Leave Date
123456 | user1 | 01/01/2017 - 01/03/2017
答案 0 :(得分:2)
假设找到的最高日期被视为date to
,最低被视为date from
SELECT b.RequestNo, a.User, CAST(MIN(Date) AS NVARCHAR(10)) + ' - ' + CAST(MAX(Date) AS NVARCHAR(10)) as Leave_Date
FROM
LeaveMain a inner join LeaveDetail b on a.RequestNo = b.requestNo
GROUP BY b.RequestNo, a.user
答案 1 :(得分:2)
使用MIN和MAX聚合函数:
SELECT RequestNo , User , CONVERT(VARCHAR, Mindate, 101) + ' - '
CONVERT(VARCHAR, Maxdate, 101)
FROM LeaveMain M
JOIN
(
SELECT RequestNo , MIN(Date) Mindate , MAX(date) Maxdate
FROM LeaveDetail
GROUP BY RequestNo
) A ON A.RequestNo = M.RequestNo
答案 2 :(得分:1)
只需将结果分组到RequestNo
并获取Min
和Max
日期:
SELECT RequestNo,
User,
CONVERT(varchar, MIN(Date), 101)
+ ' - ' CONVERT(varchar, MAX(Date), 101)
FROM LeaveMain LM
INNER JOIN LeaveDetail LD ON LM.RequestNo = LD.RequestNo
GROUP BY LM.RequestNo, LM.User
答案 3 :(得分:1)
只需使用Join
Group by
以及Max
和Min
函数作为下一个演示: -
<强>演示: - 强>
Create table #LeaveMain ([user] nvarchar(10), RequestNo int)
insert into #LeaveMain values ('user1', 123456)
Create table #LeaveDetail ( RequestNo int, [Date] date)
insert into #LeaveDetail values (123456, '01/01/2017')
insert into #LeaveDetail values (123456, '01/02/2017')
insert into #LeaveDetail values (123456, '01/03/2017')
select
Max(D.RequestNo) RequestNo ,
Max([User]) [User] ,
Convert(nvarchar(10),Min([Date])) + ' - '
+ Convert(nvarchar(10),Max([Date])) [Leave Date]
from #LeaveMain M inner join #LeaveDetail D
on M.RequestNo = D.RequestNo
group by D.RequestNo
<强>结果: - 强>
RequestNo | User | Leave Date
123456 | user1 | 01/01/2017 - 01/03/2017
答案 4 :(得分:1)
;WITH LeaveMain([User],RequestNo)
AS
(
SELECT 'user1' , 123456
)
,LeaveDetail(RequestNo , Date)
AS
(
SELECT 123456, '01/01/2017' union all
SELECT 123456, '01/02/2017' union all
SELECT 123456, '01/03/2017'
)
SELECT RequestNo,[User],CONCAT(MinDate,' - ',MaxDate)AS LeaveDate From
(
SELECT m.[User], m.RequestNo ,MAX(d.[Date])MaxDate,MIn(d.[Date])MinDate from LeaveMain m
INNER JOIN LeaveDetail d
on m.RequestNo=d.RequestNo
group by m.[User], m.RequestNo
)Dt
答案 5 :(得分:1)
尝试使用大量数据,
declare @LeaveDetail table(RequestNo varchar(20),Dates date)
insert into @LeaveDetail VALUES
('123456','2017/01/01')
,('123456','2017/01/02')
,('123456','2017/01/03')
declare @LeaveMain table(Users varchar(20),RequestNo varchar(20))
insert into @LeaveMain VALUES
('user1','123456')
select lm.Users,RequestNo
,(select convert(varchar(10),min(Dates),101)+' - '+convert(varchar(10),max(dates),101)
from @LeaveDetail ld where ld.RequestNo=lm.RequestNo )[Leave Date]
from @LeaveMain lm