对一个透视表进行分组

时间:2016-06-01 15:33:45

标签: sql-server sql-server-2008-r2 group-by pivot-table

我想将下表分为两个范围。为此,我转动了表格,但它显示了一些NULL字段。我如何对表进行分组,以便只向我显示非空值?

这是SQL查询:

SELECT RangoCuotas, [0   -21  ],[21  -42  ],[42  -79  ],[79  -158 ],[158  -9999]
FROM(
    SELECT IdTasaSeguro, Valor, CONVERT(CHAR(4),MontoMinimo)+'-'+CONVERT(CHAR(4),MontoMaximo) AS RangoMonto, CONVERT(CHAR(4),CASE WHEN CuotaMin = 0 THEN 1 ELSE CuotaMin END)+'-'+CONVERT(CHAR(4),CuotaMax) AS RangoCuotas
    FROM [BEFE_SistemaGestionMDP].[dbo].[TasaSeguro]
    WHERE IdTipoSeguro = 1
) AS SourceTable
PIVOT 
(
SUM(Valor) FOR RangoMonto IN ([0   -21  ],[21  -42  ],[42  -79  ],[79  -158 ],[158 -9999])
) AS PivotTable1
GROUP BY RangoCuotas,[0   -21  ],[21  -42  ],[42  -79  ],[79  -158 ],[158 -9999]

Table Result

1 个答案:

答案 0 :(得分:2)

如果您使用SELECT作为主(...) SourceTable语句,那么您就会看到原因。

解决方案:从IdTasaSeguro派生的表中删除不必要的列(例如FROM( SELECT Valor, CONVERT(CHAR(4),MontoMinimo)+'-'+CONVERT(CHAR(4),MontoMaximo) AS RangoMonto, CONVERT(CHAR(4),CASE WHEN CuotaMin = 0 THEN 1 ELSE CuotaMin END)+'-'+CONVERT(CHAR(4),CuotaMax) AS RangoCuotas FROM [BEFE_SistemaGestionMDP].[dbo].[TasaSeguro] WHERE IdTipoSeguro = 1 ) AS SourceTable

{{1}}