2011-05-06 65 views
0

HI(通過與具有MAX組),SQL服務器 - 查詢幫助

我在與一個查詢一個巨大的問題,這是我在我的表中的數據:

entityId    groupId    groupDepth 
-------------------- -------------------- ----------- 
NULL     1090     0 
56     1090     1 
222     1090     1 
226     1090     1 
227     1090     1 
228     1090     1 
234     1090     1 
248     1090     2 
249     1090     2 
250     1090     2 
251     1090     2 
252     1090     1 
256     1090     1 
261     1090     1 
288     1090     1 
294     1090     1 
300     1090     1 
4691     1090     1 
4694     1090     1 
4697     1090     1 

所以我想要做的是在給定entityId和groupId時獲得groupDepth最高的行。示例結果:

input: entityId = 294, groupId = 1090 
entityId    groupId    groupDepth 
-------------------- -------------------- ----------- 
294     1090     1 


input: entityId = 113, groupId = 1090 
entityId    groupId    groupDepth 
-------------------- -------------------- ----------- 
NULL     1090     0 

我在想是這樣的:

SELECT * FROM [dbo].[EntityGroup] a 
WHERE EXISTS 
(
    SELECT groupId 
    FROM  [dbo].[EntityGroup] b 
    WHERE  
       (b.entityId is null or b.entityId = 294) AND 
       b.groupId = a.groupId 
    GROUP BY b.groupId 
    HAVING a.groupDepth = max(b.groupDepth) and 
       a.entityId = b.entityId 
) 

任何幫助將不勝感激!

回答

2
SELECT entityID, groupId, groupDepth 
FROM EntityGroup t 
WHERE groupDepth = (SELECT MAX(groupDepth) FROM EntityGroup e WHERE COALESCE(e.entityID,-1) = COALESCE(t.entityId,-1) AND e.groupId = t.groupID) 
GROUP BY entityID, groupId, groupDepth 

如果我正確

編輯

SELECT entityID, groupId, groupDepth 
FROM EntityGroup t 
WHERE groupDepth = (SELECT MAX(groupDepth) FROM @Temp e WHERE e.entityID = t.entityId AND e.groupId = t.groupID) 
GROUP BY entityID, groupId, groupDepth 
UNION 
SELECT entityID, groupId, groupDepth 
FROM EntityGroup t 
WHERE groupDepth = (SELECT MAX(groupDepth) FROM @Temp e WHERE e.groupId = t.groupID AND e.entityId IS NULL) AND t.entityId IS NULL 
GROUP BY entityID,groupId, groupDepth 
+0

如果我指定不中EntityGroup表中存在ENTITYID,我將不會收到NULL行 - 請參閱我的第二個示例 – MonkeyCoder 2011-05-06 08:08:25

+0

查看我所做的更新是否有幫助 – 2011-05-06 08:14:35

0

這個怎麼理解,你應該工作?

DECLARE @entityId INT = 294 
DECLARE @groupId INT = 1090 

SELECT TOP 1 entityId, groupid, Max(groupDepth) AS groupDepth 
FROM EntityGroup 
WHERE (entityId is null OR entityId = @entityId) 
AND groupId = @groupId 
GROUP BY entityId, groupId 
order by entityId desc 

編輯:更新SQL通過ENTITYID以降序排列,並採取第一個會給出正確的答案指定的情況下

+0

這很好,我在結果集中得到了兩行 - 一個NULL值爲entityId,一個帶有294當我應該只有一行。 – MonkeyCoder 2011-05-06 08:17:38

+0

@MonkeyCoder - 對。我已經編輯了答案,現在只有1行 – Catch22 2011-05-06 09:06:20