2017-05-16 42 views

回答

2
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 
+0

它的工作。謝謝 –

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

我認爲這是最好的答案。你應該花一些時間來格式化它,或者添加評論 –

1
;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 
相關問題