通过排除Null -sql组

时间:2013-02-14 12:36:20

标签: sql-server-2008 tsql group-by common-table-expression

我的脚本如下:

    ;;WITH CTE AS
    (
        SELECT 
                RANK() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC,MAX(SecurityName)) AS [Rank]
            ,   ReportingDate
            ,   PortfolioID
            ,   PortfolioNme
            ,   MAX(SecurityName)                               AS SecurityName
            ,   CAST(SUM(Percentage) AS DECIMAL(22,1))          AS [Weight]
            ,   SEDOL
            ,   MAX(ISIN)                                       AS ISIN
        FROM @Worktable as WT

        WHERE WT.IssueType2 <> '010' AND WT.IssueType2 <> '055' AND WT.IssueType1 <> '110' -- To remove CASH and FX and Collateral

        GROUP BY    WT.ReportingDate
                ,   WT.PortfolioID
                ,   WT.PortfolioNme
                ,   WT.SEDOL
    )

    SELECT 
          CONVERT(VARCHAR, ReportingDate, 103)  AS ReportingDate
        , PortfolioID                           AS FundCode
        , PortfolioNme                          AS FundName
        , SecurityName                          AS InstrumentName
        , [Rank]
        , [Weight]                              AS Percentage
        , SEDOL
        , ISIN
    FROM CTE

    WHERE [Rank] <= 10

    ORDER BY ReportingDate, PortfolioID, [Rank], [Weight] DESC

我正在按照SEDOL进行分组,因为我想将相同的SEDOL组合在一起,但这会导致NULLS组合在一起。我试过通过在SEDOL周围添加一个MAX来改变脚本并放置:

CASE 
    WHEN SEDOL IS NULL THEN SecurityName 
    ELSE SEDOL
END

在我的GROUP BY中但没有成功。

任何帮助都非常感激。

由于

2 个答案:

答案 0 :(得分:1)

听起来您只想在CTE AND WT.SEDOL is not null子句中添加WHERE

答案 1 :(得分:0)

怎么样:

;;WITH CTE AS
    (
        SELECT 
                RANK() OVER (PARTITION BY PortfolioID ORDER BY SUM(Percentage) DESC,MAX(SecurityName)) AS [Rank]
            ,   ReportingDate
            ,   PortfolioID
            ,   PortfolioNme
            ,   MAX(SecurityName)                               AS SecurityName
            ,   CAST(SUM(Percentage) AS DECIMAL(22,1))          AS [Weight]
            ,   ISNULL(SEDOL, SecurityName) AS SEDOL
            ,   MAX(ISIN)                                       AS ISIN
        FROM @Worktable as WT

        WHERE WT.IssueType2 <> '010' AND WT.IssueType2 <> '055' AND WT.IssueType1 <> '110' -- To remove CASH and FX and Collateral

        GROUP BY    WT.ReportingDate
                ,   WT.PortfolioID
                ,   WT.PortfolioNme
                ,   ISNULL(WT.SEDOL, SecurityName)
    )

    SELECT 
          CONVERT(VARCHAR, ReportingDate, 103)  AS ReportingDate
        , PortfolioID                           AS FundCode
        , PortfolioNme                          AS FundName
        , SecurityName                          AS InstrumentName
        , [Rank]
        , [Weight]                              AS Percentage
        , SEDOL
        , ISIN
    FROM CTE

    WHERE [Rank] <= 10

    ORDER BY ReportingDate, PortfolioID, [Rank], [Weight] DESC