2017-05-02 22 views
1

ユーザーの休暇の最小日から最大日を示す列を使用して出力を生成するにはどうすればよいですか? RequestNoSQL Serverで1つの行に日付を表​​示するクエリ

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 

答えて

1

だけのグループあなたの結果とはMinMax日付を取る:

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 
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 
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 
1

単にGroup byMaxJoinを使用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 
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 
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 
関連する問題