sql - 如何使用sql在父母中获取孩子的孩子值
问题描述
我对 SQL 不是很熟悉。
我有 3 张桌子,每张桌子都是一对多的。意味着一个History
有很多Applications
,但一个Application
有很多ApplicationAttributes
。
我需要在每个请求中显示EnrolledTotal
列,其中名称。Histories
History
Application
LIKE = '%Enrollment%'
请问有人可以帮我吗?
历史表:
Id Imei CreationDate DeviceId
1 ProductionDevice299 2018-11-04 1
7 ProductionDevice300 2018-11-09 1
应用表:
Id Name DeviceHistoryId
1 Enrollment.cone 1
2 DPC_OWNERS 1
3 OTHER_APPS 1
6 Enrollment.emp 7
7 DPC_OWNERS 7
应用属性表:
Id Key Value DeviceApplicationId
1 EnrolledTotal 2 1
2 LoginsTotal 5 2
3 OtherAttribt1 8 3
4 OtherAttribt2 12 3
5 OtherAttribt3 17 3
6 EnrolledTotal 21 6
7 LoginsTotal 25 7
预期结果:
Id Imei CreationDate DeviceId EnrolledTotal
1 ProductionDevice299 2018-11-04 1 2
7 ProductionDevice300 2018-11-09 1 21
我当前的 sql 查询:
SELECT
[Extent1].[Id] AS [id],
[Extent1].[Imei] AS [imei],
CAST([Extent1].[CreationDate] AS DATE) AS [lastSeenOnline],
[Extent1].[DeviceId] AS [deviceId]
FROM [DeviceManagement].[dbo].[DeviceHistory] AS [Extent1]
INNER JOIN (
SELECT [Imei], max([CreationDate]) as MaxDate
FROM [dbo].[DeviceHistory]
GROUP BY [Imei], CAST([CreationDate] AS DATE)
) [Extent2] on [Extent1].[Imei] = [Extent2].[Imei] and [Extent1].[CreationDate] = [Extent2].MaxDate
解决方案
这似乎是一个JOIN
和GROUP BY
查询:
select h.Id, h.Imei, h.CreationDate, h.DeviceId,
sum(cast(aa.value as int)) as num_enrolled
from histories h join
applications a
on a.DeviceHistoryId = h.id join
ApplicationAttributes aa
on aa.DeviceApplicationId = a.id and
aa.key = 'EnrolledTotal'
group by h.Id, h.Imei, h.CreationDate, h.DeviceId;
推荐阅读
- php - Codeigniter- call_user_func_array() 期望参数 1 是一个有效的回调,类 'Error' 没有方法 'index'
- javascript - 通过 WebPack 将 Bootstrap 加载到 Wordpress 时,ReactJS 代码拆分导致错误
- google-apps-script - 获取值跳过错误
- swiftui - SwiftUI:API 调用后如何移动 MapPin?
- javascript - 跳过字符串的一部分并用正则表达式替换匹配
- android-studio - Android Studio 4.0.1 丢弃连接的设备
- c++ - 根据模板类型使类成员变量可选的非详细解决方案?
- javascript - 获取端点时,Spotify API 收到错误“未提供令牌”
- java - 什么客户端 Linux / Liberty / HttpComponents 配置可以防止请求被错误识别为小窗口攻击?
- python-3.x - 有人可以帮我找到一种方法将列表扩展到特定索引处的另一个列表吗?