【问题标题】:Kusto SubQuery Referencing "outer" queryKusto 子查询引用“外部”查询
【发布时间】:2021-04-21 16:15:07
【问题描述】:

我正在尝试编写一个 Kusto (KQL) 查询,在 SQL 中我会使用一个引用“外部”查询的子查询来编写,如下所示。但是,我无法找到/理解如何在 KQL 中完成等效操作。是否可以让子查询引用 KQL 中的“外部”查询?如果没有,还有其他方法可以完成以下操作吗?

基本思想是将表连接到自身以获得下一个时间值。 IE 返回时间大于当前记录时间且匹配键(本例中为DeviceName)的最小时间值。

DECLARE @DeviceIPs TABLE (DeviceName NVARCHAR(MAX), DeviceIP NVARCHAR(MAX), TimeGenerated DATETIME)

INSERT INTO @DeviceIPs SELECT 'PC1', '192.168.100.1', '2021-01-01'
INSERT INTO @DeviceIPs SELECT 'PC1', '192.168.100.2', '2021-01-02'
INSERT INTO @DeviceIPs SELECT 'PC1', '192.168.100.3', '2021-01-03'
INSERT INTO @DeviceIPs SELECT 'PC2', '192.168.100.3', '2021-01-01'
INSERT INTO @DeviceIPs SELECT 'PC2', '192.168.100.1', '2021-01-02'
INSERT INTO @DeviceIPs SELECT 'PC2', '192.168.100.2', '2021-01-03'

SELECT
    i.DeviceName,
    i.DeviceIP,
    i.TimeGenerated AS BeginDateTime,
    ISNULL((SELECT MIN(i2.TimeGenerated) FROM @DeviceIPs i2 WHERE i.DeviceName = i2.DeviceName AND i.TimeGenerated < i2.TimeGenerated), '2200-01-01') AS EndDateTime
FROM
    @DeviceIPs i

在上述数据结构中,每一行代表设备被授予 IP 地址的时间 (BeginDateTime)。然后我正在寻找的结果是还获得“EndDateTime”,这将是下一次授予设备 IP 地址的时间。如果没有“下一条记录”,我只是将一些随机的未来日期设置为结束日期,但这部分与这个问题并不真正相关。预期的结果是:

DeviceName DeviceIP BeginDateTime EndDateTime
PC1 192.168.0.1 2021-01-01 2021-01-02
PC1 192.168.0.2 2021-01-02 2021-01-03
PC1 192.168.0.3 2021-01-03 2200-01-01
PC2 192.168.0.3 2021-01-01 2021-01-02
PC2 192.168.0.1 2021-01-02 2021-01-03
PC2 192.168.0.2 2021-01-03 2200-01-01

【问题讨论】:

    标签: azure-data-explorer kql


    【解决方案1】:

    假设我正确理解了您的意图,以下应该有效:

    .create table DeviceIPs (DeviceName:string, DeviceIP: string, TimeGenerated:datetime)
    
    .ingest inline into table DeviceIPs <|
    PC1,192.168.100.1,2021-01-01
    PC1,192.168.100.2,2021-01-02
    PC1,192.168.100.3,2021-01-03
    PC2,192.168.100.3,2021-01-01
    PC2,192.168.100.1,2021-01-02
    PC2,192.168.100.2,2021-01-03
    
    DeviceIPs
    | order by DeviceName asc, TimeGenerated asc
    | project DeviceName, DeviceIP, BeginDateTime = TimeGenerated, EndDateTime = case(next(DeviceName) == DeviceName, next(TimeGenerated), datetime(2200-01-01))
    
    DeviceName DeviceIP BeginDateTime EndDateTime
    PC1 192.168.100.1 2021-01-01 00:00:00.0000000 2021-01-02 00:00:00.0000000
    PC1 192.168.100.2 2021-01-02 00:00:00.0000000 2021-01-03 00:00:00.0000000
    PC1 192.168.100.3 2021-01-03 00:00:00.0000000 2200-01-01 00:00:00.0000000
    PC2 192.168.100.3 2021-01-01 00:00:00.0000000 2021-01-02 00:00:00.0000000
    PC2 192.168.100.1 2021-01-02 00:00:00.0000000 2021-01-03 00:00:00.0000000
    PC2 192.168.100.2 2021-01-03 00:00:00.0000000 2200-01-01 00:00:00.0000000

    【讨论】:

    • 谢谢。我意识到我最初的描述不是很清楚。我现在已经更新它以包含预期的输出。
    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多