[英]Select detailed data from SQL Server Table related to specific months?
我在生日表中有這樣的數據
Month Employee
Jan John
Jan George
April Matt
April Maxim
我想寫一個返回的查詢
Month Employee
Jan John
George
April Matt
Maxim
DECLARE @Birthdays TABLE ( Month NVARCHAR(15), Employee NVARCHAR(20))
INSERT INTO @Birthdays
( Month, Employee )
SELECT
'Jan','John'
UNION ALL
SELECT 'Jan','George'
UNION ALL
SELECT 'April','Matt'
UNION ALL
SELECT 'April','Maxim'
;WITH cte
AS(
SELECT Month, Employee
,ROW_NUMBER()OVER(PARTITION BY Month ORDER BY Month) 'RN'
FROM @Birthdays
)
SELECT
CASE WHEN C.RN = 1 THEN C.Month ELSE '' END AS 'Month'
, C.Employee
FROM cte C
ORDER BY C.Month DESC
CREATE TABLE dbo.Birthdays (
Month VARCHAR(100)
,Employee VARCHAR(100)
);
INSERT INTO dbo.Birthdays (Month,Employee)
VALUES ('Jan','John'),( 'Jan','George'),('April','Matt'),('April','Maxim');
SELECT CASE
WHEN b.Month = LAG(b.Month, 1, 0) OVER (
ORDER BY b.Month
)
THEN ''
ELSE b.Month
END AS Month
,b.Employee
FROM dbo.Birthdays b
;With cte([Month], Employee)
AS
(
SELECT 'Jan' ,'John' Union all
SELECT 'Jan' ,'George' Union all
SELECT 'April','Matt' Union all
SELECT 'April','Maxim'
)
SELECT CASE WHEN [MonthSeq]=1 THEN [Month] ELSE '' END AS [Month], Employee From
(
Select * , ROW_NUMBER()Over(Partition by [Month] order by [Month] ) As [MonthSeq] from cte
)Dt
Order BY dt.[Month] desc
產量
Month Employee
----------------
Jan George
John
April Maxim
Matt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.