当我从数据库中提取字段时,最基本的查询如下所示:
SELECT DISTINCT
[BranchCode]
,[Weekday]
,[OpenTime]
,[CloseTime]
FROM [Departments]
WHERE [BranchCode] like '%1001.0000%'
结果是这样的:
BranchCode Weekday OpenTime CloseTime
=============================================
1001.0000 Friday 06:00 21:00
1001.0000 Monday 06:00 21:00
1001.0000 Saturday NULL NULL
1001.0000 Sunday NULL NULL
1001.0000 Thursday 08:00 17:00
1001.0000 Tuesday 08:00 17:00
1001.0000 Wednesday 08:00 17:00
我想要达到的目标
对于每个branchcode,json是否与此结果相似
"1001.0000": {
"HoursOfOpertion": {
"Monday": {
"OpenTime": "06:00",
"CloseTime": "21:00"
},
"Tuesday": {
"OpenTime": "06:00",
"CloseTime": "21:00"
},
"Wednesday": {
"OpenTime": "06:00",
"CloseTime": "21:00"
},
"Thursday": {
"OpenTime": "06:00",
"CloseTime": "21:00"
},
"Friday": {
"OpenTime": "08:00",
"CloseTime": "17:00"
},
"Saturday": {
"OpenTime": "NULL",
"CloseTime": "NULL"
},
"Sunday": {
"OpenTime": "NULL",
"CloseTime": "NULL"
}
}
}
我试过的
我已经到了死胡同 PIVOT
以及 JOIN
,我觉得我很接近,但我还是没有接近我需要的东西。
SELECT distinct
[CloseTime]
,[Sunday]
,[Monday]
,[Tuesday]
,[Wednesday]
,[Thursday]
,[Friday]
,[Saturday]
FROM [Branches] as br
LEFT JOIN(
SELECT
* FROM (
SELECT DISTINCT
[Weekday] as [WD]
,[OpenTime]
,[CloseTime]
,[Closed]
,[BranchCode]
FROM [Departments]
) AS SRC PIVOT (
MAX([OpenTime])
FOR [WD] IN (
[Sunday]
,[Monday]
,[Tuesday]
,[Wednesday]
,[Thursday]
,[Friday]
,[Saturday]
)
) as PVT
) p
on p.[BranchCode] = br.[BranchCode]
where br.[BranchCode] like '%1001.0000%'
FOR JSON PATH
它给了我这样的东西:
[
{
"CloseTime":"1700",
"Monday":"0800"
},
{
"CloseTime":"1700",
"Tuesday":"0800"
},
{
"CloseTime":"1700",
"Wednesday":"0800"
},
{
"CloseTime":"1700",
"Thursday":"0800"
},
{
"CloseTime":"1700",
"Friday":"0800"
},
{
"CloseTime":"1800",
"Saturday":"0800"
}
]
1条答案
按热度按时间rdlzhqv91#
这里有两个解决方案可以让你接近。
样本数据:
第一种方法更像是一种动态的方法,但与预期结果有点偏差,但需要的代码更少。
第二种方法的动态性较差,但更接近您的示例。因为sql使用表名作为元素名,所以很难为每个分支提供一个命名元素。我们可以在工作日这样做,因为它们是已知常数。因此,实际上,您只需要得到一个具有分支代码属性和操作时间的分支对象数组。样本数据也可用于此解决方案。