【问题标题】:SQL Server query to hide duplicate rows column data. Don't want to remove a duplicate rowSQL Server 查询隐藏重复行列数据。不想删除重复的行
【发布时间】:2025-12-15 16:55:02
【问题描述】:

SQL Server 查询隐藏重复行列数据。不想删除重复的行。有条件地将数据显示为空白。

什么时候,我运行这个 SQL 查询:

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

我得到这个输出:

但是,我需要这种格式的输出:

在第二个打印屏幕中,我没有显示 [Vch Ref]、[Date]、[Party Name]、[Sales Ledger]、[Amt] 和 Total 的值。

【问题讨论】:

  • 你真的应该在应用层而不是在数据库中这样做。
  • 我正在将数据导出到 excel 并且中间没有应用层。
  • 它们并不是真正重复的行,因为 GST 分类帐不同并且您想要显示它
  • 是的,我想要 GST 分类帐和 GST 列不重复。

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


【解决方案1】:

这看起来像是一种疯狂的解决方案,但您可以使用窗口函数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,如果你想获得空白值,则应将其转换为字符串。

【讨论】: