2017-08-01 21 views
1

SQL Server查詢可以隱藏重複行的列數據。不想刪除重複的行。有條件地將數據顯示爲空白。用於隱藏重複行列數據的SQL Server查詢。不想刪除重複行

當我運行這個SQL查詢:

select 
    [Vch No.], [Vch Type], [Vch Ref], 
    [Date], [Party Name], [Sales Ledger], 
    [Amt], [GST Ledger], [TaxAmount], [Total] 
from 
    [AccountData] 

我得到這樣的輸出:

enter image description here

但是,我需要這種格式輸出:

enter image description here

在第二個打印屏幕,我無法顯示[Vch參考],[日期],[派對名稱],[銷售分類帳],[金額]和總金額。

+4

您應該在應用程序層而不是數據庫中執行此操作。 –

+0

我正在將數據導出爲ex​​cel,並且沒有應用程序層。 –

+0

他們不是真正重複的行,因爲GST分類賬是不同的,並且您想要顯示那 –

回答

2

這看起來像瘋了一個解決方案,但可以使用窗口函數ROW_NUMBER()和使用CASE表達檢查,如果行數大於1,像實現它:

select 
    [Vch No.], 
    [Vch Type], 
    case when rn > 1 then '' else [Vch Ref] end as [Vch Ref], 
    case when rn > 1 then '' else [Date] end as [Date], 
    case when rn > 1 then '' else [Party Name] end as [Party Name], 
    case when rn > 1 then '' else [Sales Ledger] end as [Sales Ledger], 
    case when rn > 1 then '' else [Amt] end as [Amt], 
    [GST Ledger], 
    [TaxAmount], 
    case when rn > 1 then '' else [Total] end as [Total] 
from ( 
    select 
     [Vch No.], 
     [Vch Type], 
     [Vch Ref], 
     [Date], 
     [Party Name], 
     [Sales Ledger], 
     [Amt], 
     [GST Ledger], 
     [TaxAmount], 
     [Total], 
     row_number() over (partition by [Vch No.],[Vch Type],[Vch Ref],[Date],[Party Name],[Sales Ledger],[Amt],[GST Ledger],[TaxAmount],[Total] order by [Vch No.]) rn 
    from [AccountData] 
)x 

看看數據類型,如果有Amt是INT你應該將其轉換爲字符串,如果你想獲得空白值。