【问题标题】:Selecting two sets of data individually grouped选择单独分组的两组数据
【发布时间】:2011-09-13 21:52:11
【问题描述】:

使用以下查询以 15 分钟间隔从表中选择一个点的 state=1 的数据:

SELECT * , ROUND( UNIX_TIMESTAMP( log_date ) / ( 15 *60 ) ) AS period
FROM  `site_node_point_states` 
WHERE state =1
AND site_node_point_id =  "11"
AND log_date
BETWEEN  '2011-09-12 13:00:00'
AND  '2011-09-12 13:00:00'
GROUP BY period
ORDER BY period ASC

此查询完全基于单个 site_node_point_id 执行我想要的操作,但是我希望能够添加另一个 site_node_point_id 并将其按 period 单独分组到其他 site_node_point_id 数据。

我正在使用 PHP 进行此查询,并想尝试将其限制为单个查询,而不是使用不同的 site_node_point_id 循环遍历我当前的查询。

显然,如果我将 AND site_node_point_id = "11" 更改为 AND site_node_point_id = "11" OR site_node_point_id = "14",它将从 site_node_point_id 14 和 11 订购数据。

SQL 中是否有解决方案可以根据我选择的site_node_point_id 为每组数据单独执行GROUP BY?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    使用GROUP BY site_node_point_id, period。这应该首先按 site_node_point_id 对结果进行分组,然后是句点。

    【讨论】:

    • 这对我有用,我可以发誓我一开始就尝试过。但这可能只是因为疲倦。谢谢。
    • @N1ck:你可以通过正式的accepting 来感谢答案。这是一种非常成熟的(也很好)的感谢形式。 :)
    【解决方案2】:

    这可能是您正在寻找的:

    SELECT * , ROUND( UNIX_TIMESTAMP( log_date ) / ( 15 *60 ) ) AS period
    FROM  `site_node_point_states` 
    WHERE state =1
    AND site_node_point_id in ("11", "12")
    AND log_date
    BETWEEN  '2011-09-12 13:00:00'
    AND  '2011-09-12 13:00:00'
    GROUP BY site_node_point_id, period
    ORDER BY site_node_point_id, period ASC
    

    【讨论】:

      猜你喜欢
      • 2016-03-04
      • 1970-01-01
      • 2012-12-27
      • 2021-11-17
      • 1970-01-01
      • 2015-04-07
      • 2022-10-05
      • 1970-01-01
      • 2017-04-09
      相关资源
      最近更新 更多