选择发生列值更改的行

时间:2016-03-22 09:42:42

标签: sql sql-server sql-server-2012

我有如下所示的数据。它是由以下查询产生的:

;with noms as
(
    select DateS, Region, Sales from tblSalesRegion
    where Id = 'B2PM' 
)
select * from
noms as source pivot (max(Sales) for Region in ([UK],[US],[EUxUK],[JAP],[Brazil])) as pvt
order by DateS

数据:

 DateS      UK      US      EUxUK   JAP     Brazil
 2015-11-24 23634   22187   NULL    NULL    NULL
 2015-11-30 23634   22187   NULL    NULL    NULL
 2015-12-01 23634   22187   NULL    NULL    NULL
 2015-12-02 23634   22187   NULL    NULL    NULL
 2015-12-03 23634   22187   NULL    NULL    NULL
 2015-12-04 56000   22187   NULL    NULL    NULL
 2015-12-07 56000   22187   NULL    NULL    NULL
 2015-12-08 56000   22187   NULL    NULL    NULL
 2015-12-09 56000   22187   NULL    NULL    NULL
 2015-12-10 56000   10025   NULL    NULL    NULL
 2015-12-11 56000   10025   NULL    NULL    NULL
 2015-12-14 56000   10025   NULL    NULL    NULL

以下是我追求的结果。所以基本上当其中一个值在五列之一(不包括dateS列)中发生变化时,我希望显示它。有没有办法在Sql中执行此操作?由于我需要日期,我不认为一个简单的分组声明会起作用。如果我可以将NULL更改为零

,那也很好

结果我正在寻找:

 DateS      UK      US      EUxUK   JAP     Brazil
 2015-11-24 23634   22187   0       0       0
 2015-12-04 56000   22187   0       0       0
 2015-12-10 56000   10025   0       0       0

1 个答案:

答案 0 :(得分:1)

看起来像一个简单的GROUP BY就是你想要的:

;WITH noms AS
(
    SELECT DateS, Region, Sales 
    FROM tblSalesRegion
    WHERE Id = 'B2PM' 
) 
SELECT MIN(DateS), [UK],[US],[EUxUK],[JAP],[Brazil]
FROM ( 
   SELECT DateS, 
          COALESCE([UK], 0) AS [UK],
          COALESCE([US], 0) AS [US],
          COALESCE([EUxUK], 0) AS [EUxUK],
          COALESCE([JAP], 0) AS [JAP],
          COALESCE([Brazil], 0) AS [Brazil]
   FROM noms AS source 
   PIVOT (
      MAX(Sales) FOR Region IN ([UK],[US],[EUxUK],[JAP],[Brazil])) AS pvt
) AS t
GROUP BY [UK],[US],[EUxUK],[JAP],[Brazil] 
ORDER BY MIN(DateS)