3

在下面的查询中,对于 o.EventSetName、o.EventSetDisplay、o.EventSetDescription - 任何时候结果中的 3 列都有重复的 ROWS - 只有第一个这样的行应该显示,其余重复行为空白... ..

这是sql:

 Select  distinct top 100000 o.EventSetName,       
                             o.EventSetDisplay,
                             o.EventSetDescription,
                             o.ChildSetName,
                             ROW_NUMBER() Over (Order By f.ChildSetName) RN,
                             f.DocumentDispSequence,
                             f.SectionDispSequence,
                             o.ObsSetDispSequence,
                             null                          
                      From   ##ObsSetLevel o,
                             ##Final f
                      Where  f.ChildSetName = o.EventSetName and 
                             o.EventSetName = @variableName
                      Order By RN asc, f.DocumentDispSequence asc, f.SectionDispSequence asc, o.ObsSetDispSequence asc

我没有报告工具,所以现在很多报告逻辑需要在存储过程本身中完成......

所以而不是:

val 1   val2    val3  val7
val 1   val2    val3  val8
val 1   val2    val3  val 10
val 1   val2    val3  x
val 1   val2    val3  y

我应该得到第 2、3、4 和 5 行前 3 列的空白结果

4

1 回答 1

5

将现有查询包装在 CTE 中,添加ROW_NUMBER OVER PARTITION BY列,这将为每组值创建 RN。在外部查询中,只需使用 CASE 选择 GRP_RN = 1 的值,否则选择空字符串。

WITH CTE AS 
(
    Select  distinct top 100000 
        o.EventSetName,       
        o.EventSetDisplay,
        o.EventSetDescription,
        o.ChildSetName,
        ROW_NUMBER() Over (Order By f.ChildSetName) RN,
        f.DocumentDispSequence,
        f.SectionDispSequence,
        o.ObsSetDispSequence,
        null  as NullColumnNeedsName,
        ROW_NUMBER() OVER (PARTITION BY o.EventSetName, o.EventSetDisplay,o.EventSetDescription ORDER BY f.ChildSetName) GRP_RN
    From   ##ObsSetLevel o,
    INNER JOIN ##Final f ON f.ChildSetName = o.EventSetName and o.EventSetName = @variableName
)
SELECT
    CASE WHEN GRP_RN = 1 THEN o.EventSetName ELSE '' END AS EventSetName,
    CASE WHEN GRP_RN = 1 THEN o.EventSetDisplay ELSE '' END AS EventSetDisplay,
    CASE WHEN GRP_RN = 1 THEN o.EventSetDescription ELSE '' END AS EventSetDescription,
    other columns
FROM CTE  
Order By RN asc, DocumentDispSequence asc, SectionDispSequence asc, o.ObsSetDispSequence asc

PS:我还更正了您对旧式联接的使用。随着 SQL-92 标准的引入,这种用法在 20 多年前就已经过时了。你应该避免使用它们。

于 2013-09-12T15:28:25.297 回答