0

I have 2 tables:

attribuut

attribuutvalue

They have a one-to-many relationship. An attribuut can have multiple attribuutvalues. These attribuutvalues contain states.

Now I want a query which gives me back the latest attribuutvalue from an attribuut, which has: state 3 or state 6.

Then i hit my problem: When an attribuut contains an attribuutvalue with state 4, only the latest attribuutvalue with state 3 should be shown.

SELECT DISTINCT * FROM attribuut as att
LEFT JOIN attribuutvalue as value ON (value.attribuuthead = att.displayid)
WHERE value.status = 3 OR (value.status = 6 
AND NOT EXISTS 
    (SELECT * FROM attribuutvalue as value2 WHERE value2.valueid = value.valueid AND value2.status = 4)) 
ORDER BY valueid DESC

However this gives me not the resultset i want. There are still attribuutvalues with state 4 shown. And it doesnt give me only the last record in the list...

4

1 回答 1

1

您遇到的第一个问题是在您的NOT EXISTS子查询中。您应该加入attribuuthead而不是加入valueid(我认为这是该表上的唯一键)

其次,您缺少一种仅过滤每个attribuuthead. ROW_NUMBER()可以做到这一点。

所以固定查询可能如下所示:

SELECT * FROM 
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY attribuuthead ORDER BY valueid DESC) RN
    FROM dbo.attribuutvalue v
    WHERE STATUS = 3 OR (Status = 6 AND NOT EXISTS (SELECT * FROM attribuutvalue v2 WHERE v2.attribuuthead = v.attribuuthead AND v2.STATUS = 4))
) x
INNER JOIN attribuut a ON x.attribuuthead = a.displayid
WHERE x.RN = 1

SQLFiddle 演示

于 2013-07-17T12:34:20.620 回答