【问题标题】:SQL Query assistance - Looping through data querySQL 查询辅助 - 循环数据查询
【发布时间】:2017-12-10 10:59:54
【问题描述】:

我有两张桌子。配置和数据。配置表包含定义我所说的“预定义点”的信息。这些列是 configId、machineId、iotype、ioid、subfield 和 predeftype。我有第二个表,其中包含由 configId 链接的配置表中所有项目的所有数据。数据表包含configId、timestamp、value。

我试图从配置表中返回每一行,结果中包含 2 个新列,这将是该特定预定义点的最小时间戳和该特定预定义点的最大时间戳。

伪代码是

select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId where configId = (select configId from TrendConfig)

子查询将返回多个值。

知道如何制定这个吗?

【问题讨论】:

  • 请向我们展示表格结构,以便给出准确的答案。这很可能可以通过连接或相关子查询来完成。
  • 听起来你在谈论加入-w3schools.com/sql/sql_join.asp
  • 蒂姆,我附上了结构的图像。
  • 杰夫,确实,但我最大的问题是如何从配置表中获取所有项目并获取每个项目的最小/最大时间戳,这对我来说是困难的部分。假设配置中有 2 个项目(configId = 1,configId = 2)。我需要从 Config 中获取所有行,其中 configId = 1 和 min(timestamp) 的新列,其中 configId = 1 和 max(timestamp),其中 configId = 1,然后在第二行再次获取 configId = 2 的新列。
  • 您希望每个值都有一个输出行吗?听起来像 GROUP BY。

标签: sqlite


【解决方案1】:

我能够使用以下方法找到答案:Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?

解决方案确实是上面提到的 CL 的 GROUP BY。

select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId group by a.configId

【讨论】:

    【解决方案2】:

    尝试内连接:

    选择 a.*, b.min(timestamp), b.max(timestamp) 从配置一个 内连接数据 b a.configId = b.configID

    【讨论】:

    • 它与 min(b.timestamp) 和 max(b.timestamp) 一起运行,但只返回一个结果......因为它只获取所有点的最大值/最小值,而不是每个点在配置表中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 2017-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多