简体   繁体   English

如何使用存储过程在 sql server 中 PIVOT 表?

[英]How to PIVOT table in sql server using stored procedure?

My Stg table looks like,
Com_key  metric_name  metric_value  metric_date
   A        bugs           1        2020-06-09T16:26:41+0000
   A        bugs           1        2020-06-09T16:31:55+0000
   B        bugs           0        2020-06-18T13:59:28+0000
   B        bugs           1        2020-06-18T14:11:13+0000
   C        bugs           1        2020-06-15T14:27:32+0000
My fact table should look like,

com_key    bugs_cnt   metric_date
   A           1      2020-06-09T16:31:55+0000  
   B           0      2020-06-18T13:59:28+0000
   B           1      2020-06-18T14:11:13+0000
   C           1      2020-06-15T14:27:32+0000

I need to write a stored procedure to PIVOT table in sql server for the below explained scenario.对于下面解释的场景,我需要在 sql server 中为 PIVOT 表编写一个存储过程。 When duplicate record comes on same day I need to consider only the last modified date.当重复记录出现在同一天时,我只需要考虑最后修改的日期。 In the above example there is a duplicate record for com_key A with same metric_date and different time and I need to consider only the latest updated value, but at the same time need to retain the com_keys with diff metric values which comes on the same day with different time.在上面的例子中,com_key A 有一个重复的记录,具有相同的 metric_date 和不同的时间,我只需要考虑最新的更新值,但同时需要保留 com_keys 与同一天出现的不同度量值不同的时间。

Thanks in advance.提前致谢。

What pivot?什么支点? this looks like filtering:这看起来像过滤:

select Com_key, metric_name, metric_value, max(metric_date) as metric_date
from (select t.*,
             row_number() over (partition by Com_key, metric_name, metric_value, convert(date, metric_date) order by metric_date desc) as seqnum
      from t
     ) t
where seqnum = 1;

I also strongly discourage from putting this into a stored procedure.我也强烈反对将其放入存储过程。 If you want to store this as code, a view is quite sufficient.如果你想把它存储为代码,一个视图就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM