Search code examples
sqlsql-serversql-server-2008

Query to hide duplicate rows column data. Don't want to remove a duplicate row


I want a SQL Server query to hide duplicate rows column data. I don't want to remove the duplicate row, rather conditionally display data as blank.

When, I run this SQL query:

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

I am getting this output:

enter image description here

But, I need output in this format:

enter image description here

In the second print screen, I don't what to display a value of [Vch Ref], [Date],[Party Name], [Sales Ledger], [Amt] and Total.


Solution

  • This looks like crazy one solution, but you can achieve it using windowed function ROW_NUMBER() and using CASE expression check if row number is higher than 1, something like:

    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
    

    Look at datatypes, if there Amt is INT you should convert it to string if you want to get blank value.