SQL Server查询隐藏重复行列数据。不想删除重复的行

时间:2017-08-01 11:56:50

标签: sql sql-server database sql-server-2008

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 Ref],[Date],[Party Name],[Sales Ledger],[Amt]和Total的值。

1 个答案:

答案 0 :(得分: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,则应将其转换为字符串,如果要获取空值。