解析Json并计算SQL Server 2008R2中的值

时间:2017-12-26 14:02:09

标签: sql json sql-server sql-server-2008-r2

我正在使用SQL Server 2008 R2版本。我有一个名为Attendance的表,其中包含以下值:

Id   Date         Status
1    2017-12-20   [{"id":1,"Status":"Available"},{"id":2,"Status":"Sick Leave"},{"id":3,"Status":"Available"},{"id":4,"Status":"Available"}]
2    2017-12-21   [{"id":1,"Status":"Sick Leave"},{"id":2,"Status":"Casual Leave"},{"id":3,"Status":"Available"},{"id":4,"Status":"Available"}]

我需要的是

Date        Available   SickLeave  CasualLeave  Morning Permission Evening Permission 
2017-12-20    3           1           0               0               0
2017-12-21    3           1           1               0               0

我真的被卡住了。有人可以帮我解决这个问题。

提前致谢

1 个答案:

答案 0 :(得分:0)

我会使用xml Insert into TEST (DATE, STATUS) Values (TO_DATE('06/08/2017 17:16:16', 'MM/DD/YYYY HH24:MI:SS'), 'B'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:07', 'MM/DD/YYYY HH24:MI:SS'), 'A'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:22', 'MM/DD/YYYY HH24:MI:SS'), 'A'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:33', 'MM/DD/YYYY HH24:MI:SS'), 'A'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:40', 'MM/DD/YYYY HH24:MI:SS'), 'A'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:27:03', 'MM/DD/YYYY HH24:MI:SS'), 'A'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:13', 'MM/DD/YYYY HH24:MI:SS'), 'B'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:15', 'MM/DD/YYYY HH24:MI:SS'), 'B'); Insert into TEST (DATE, STATUS) Values (TO_DATE('04/24/2016 21:26:16', 'MM/DD/YYYY HH24:MI:SS'), 'B'); 方法和一些简单的条件聚合

.node()

结果:

select 
    a.[Date],
    sum(case when substring(s.value('.', 'varchar(100)'), 1, charindex('"', s.value('.', 'varchar(100)'))-1) = 'Available' then 1 else 0 end) [Available],
    sum(case when substring(s.value('.', 'varchar(100)'), 1, charindex('"', s.value('.', 'varchar(100)'))-1) = 'Sick Leave' then 1 else 0 end) [SickLeave],
    sum(case when substring(s.value('.', 'varchar(100)'), 1, charindex('"', s.value('.', 'varchar(100)'))-1) = 'Casual Leave' then 1 else 0 end) [CasualLeave],
    sum(case when substring(s.value('.', 'varchar(100)'), 1, charindex('"', s.value('.', 'varchar(100)'))-1) = 'Morning Permission' then 1 else 0 end) [MorningPermission],
    sum(case when substring(s.value('.', 'varchar(100)'), 1, charindex('"', s.value('.', 'varchar(100)'))-1) = 'Evening Permission' then 1 else 0 end) [EveningPermission]   from
(
    select Id, [Date], cast('<m>'+replace([Status], '":"','</m><m>')+'</m>' as xml) [Status] from Attendance
) a cross apply [Status].nodes ('/m') as aa(s)
group by a.[Date]