相关子查询 - 计数记录"小于"主查询记录

时间:2014-10-30 01:24:23

标签: mysql sql correlated-subquery

我正在尝试确定哪个"迭代"任何给定记录都是通过计算它之前的记录数量并具有某些匹配特征。基本上,我想知道具有相同父记录和记录的记录数量。 ID#小于[我的记录' ID#]的类别。我可以获得一个相关子查询来计算具有相同父级和类别的记录数,但是当我尝试添加ID过滤器时,我的子查询过滤器无法找到列" T1.ID" - 我主表中的ID#字段。

我的SQL如下,星号是我尝试过的地方,未能根据" T1"#34;记录ID(我显然在实际的SQL中排除了星号)

select T1.ID, T2.ITERATION
from TICKET as T1
inner join
(select COUNT(T3.ID) as ITERATION, T3.CATEGORY_ID, T3.PARENT_ID 
from TICKET as T3 
where T3.IS_PARENT = 0 **AND T3.ID < T1.ID**
group by T3.PARENT_ID, T3. CATEGORY_ID)
as T2 on (T1.PARENT_ID = T2.PARENT_ID AND
T1. CATEGORY_ID = T2.CATEGORY_ID)
where T1.IS_PARENT = 0

我是其他程序,我使用构建子查询的函数来完成类似的结果,所以如果我应该朝那个方向看,我会很感激这些反馈。

我从同一张桌子算起,所以样本数据:

ID   PARENT_ID    CATEGORY
10   1            A
11   2            A
12   1            B
13   3            A
14   2            A
15   1            A
16   3            B
17   1            A

期望的输出:

ID   ITERATION    (explanation)
10   0            (No preceding ID with same parent & category)
11   0            (No preceding ID with same parent & category)
12   0            (No preceding ID with same parent & category)
13   0            (No preceding ID with same parent & category)
14   1            (ID 11 precedes 14 and shares parent & category)
15   1            (ID 10 precedes 15 and shares parent & category)
16   0            (No preceding ID with same parent & category)
17   2            (ID's 10, 15 precede 17 and share parent & category)

1 个答案:

答案 0 :(得分:0)

我认为这就是你想要的:

SELECT 
    ID, 
    PARENT_ID, 
    CATEGORY, 
    (SELECT COUNT(*) FROM TICKET 
     WHERE ID < T.ID 
          AND CATEGORY = T.CATEGORY 
          AND PARENT_ID = T.PARENT_ID
     ) AS ITERATION
FROM TICKET T
ORDER BY ID

使用您的样本数据的结果:

ID  PARENT_ID   CATEGORY    ITERATION
10  1           A           0
11  2           A           0
12  1           B           0
13  3           A           0
14  2           A           1
15  1           A           1
16  3           B           0
17  1           A           2