0

我在 PHP 5.5.9 中使用 SQLite3
这是我正在使用的查询

SELECT ForignKey_A, Location_ID, TimeStamp
FROM Events
GROUP BY ForignKey_A
ORDER BY TimeStamp

我想在每组中找到最小值和/或最大值的Location_ID行(如果我可以同时做这两个很好) 我想我会根据我的排序方式获得组中的第一个值但是它不起作用,每个组通常有 2 到 6 行 我不确定该列是否对此有用,但 我确实有一个名为布尔值 1/0的列将 = 0在每个组中存在的行上. 同样will = 1在每个组中存在的行上。TimeStampForignKey_A

TimeStamp


type
typeMIN(TimeStamp)ForignKey_A
typeMAX(TimeStamp)ForignKey_A


编辑:
样本表:

╔═════════════╦═════════════╦════════════╦══════╗
║ ForignKey_A ║ Location_ID ║ TimeStamp  ║ Type ║
╠═════════════╬═════════════╬════════════╬══════╣
║           1 ║         762 ║ 1496062971 ║    0 ║
║           1 ║         427 ║ 1496063971 ║    1 ║
║           1 ║         417 ║ 1496065971 ║    0 ║
║           1 ║         123 ║ 1496072971 ║    1 ║
║           2 ║         594 ║ 1496062971 ║    0 ║
║           2 ║         427 ║ 1496072971 ║    1 ║
║           3 ║         217 ║ 1496082971 ║    0 ║
║           3 ║         356 ║ 1496092971 ║    1 ║
║           3 ║         985 ║ 1496099971 ║    0 ║
║           3 ║         789 ║ 1496162971 ║    1 ║
║           3 ║         456 ║ 1496262971 ║    0 ║
║           3 ║         123 ║ 1496362971 ║    1 ║
╚═════════════╩═════════════╩════════════╩══════╝

我确实知道如果我这样做我会得到相关的Location_ID

SELECT MIN(TimeStamp), Location_ID
FROM TableA
GROUP BY ForignKey_A

我可以从与 MIN/MAX 相同的行中获取数据TimeStamp 这得到了我需要的东西,我必须进行几个子选择查询,但它可以工作,但是有没有办法做这样的事情并得到正确的Location_ID

SELECT MIN(TimeStamp) AS 'Begin', Location_ID AS 'Location_ID @ MIN TimeStamp',
    MAX(TimeStamp) AS 'End', Location_ID AS 'Location_ID @ MAX TimeStamp', 
    ForignKey_A
FROM TableA
GROUP BY ForignKey_A

那会做这样的事情

╔═════════════╦═══════╦════════════╦══════╦════════════╗
║ ForignKey_A ║ Start ║   Begin    ║ Stop ║    End     ║
╠═════════════╬═══════╬════════════╬══════╬════════════╣
║           1 ║   762 ║ 1496062971 ║  123 ║ 1496072971 ║
║           2 ║   594 ║ 1496062971 ║  427 ║ 1496072971 ║
║           3 ║   217 ║ 1496082971 ║  123 ║ 1496362971 ║
╚═════════════╩═══════╩════════════╩══════╩════════════╝
4

1 回答 1

2

对于单个查询,无法将列值与哪个 MIN()/MAX() 关联。您必须使用子查询查找最小值和最大值,然后将这些值连接在一起:

SELECT ForeignKey_A,
       b.TimeStamp,
       b.Location_ID,
       e.TimeStamp,
       e.Location_ID
FROM (SELECT ForeignKey_A,
             min(TimeStamp) AS TimeStamp,
             Location_ID
      FROM TableA
      GROUP BY ForeignKey_A
     ) AS b
JOIN (SELECT ForeignKey_A,
             max(TimeStamp) AS TimeStamp,
             Location_ID
      FROM TableA
      GROUP BY ForeignKey_A
     ) AS e
USING (ForeignKey_A);
于 2017-05-29T13:51:00.790 回答