如何在 SQL Server 中将行转换为列? [英] How to convert rows into columns in SQL Server?

查看:35
本文介绍了如何在 SQL Server 中将行转换为列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这张来自指纹传感器的表格,我需要在一行中显示结果

I have this table from fingerprint sensor and I need to show the result in one row

ID |  DateTime                | Flag
----------------------------------------
41 |  2017-02-22 08:05:56.000 | I
41 |  2017-02-22 18:11:03.000 | O

需要这样的结果:

ID |  IN-DateTime             |  OUT-DateTime           
--------------------------------------------------------
41 |  2017-02-22 08:05:56.000 | 2017-02-22 18:11:03.000 

有人可以帮我吗?

推荐答案

简单聚合应该做到:

select id,
    max(case when flag = 'I' then datetime end) indatetime,
    max(case when flag = 'O' then datetime end) outdatetime
from t
group by id;

或者如果你愿意,你可以使用pivot:

Or If you want, you can use pivot:

select id, [I] indatetime, [O] outdatetime
from t pivot (
    max(datetime) for flag in ([I],[O])
) as p

这篇关于如何在 SQL Server 中将行转换为列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆