2013-03-12 25 views
1

我試圖創建一個查詢,該查詢返回特定實體記錄的列表而不返回實體ID字段中的任何重複條目。該查詢不能使用DISTINCT,因爲該列表正在傳遞給不理解包含多於entityID的結果集的報告引擎,並且DISTINCT要求返回所有ORDER BY字段。在不使用不同的情況下限制分組結果集中的重複結果

結果集不能包含重複的實體ID,因爲報告引擎也不能在同一次運行中兩次爲同一實體處理報告。我發現了臨時表不支持的困難方式。

條目需要在查詢中排序,因爲報表引擎只允許在entity_header級別進行排序,而且我需要根據report.status進行排序。值得慶幸的是,報表引擎會按照您返回結果的順序進行操作。

的表如下所示:

entity_header 
================================================= 
entityID(pk) Location  active  name 
1    LOCATION1  0   name1 
2    LOCATION1  0   name2 
3    LOCATION2  0   name3 
4    LOCATION3  0   name4 
5    LOCATION2  1   name5 
6    LOCATION2  0   name6 

report 
======================================================== 
startdate  entityID(fk) status  reportID(pk) 
03-10-2013  1    running  1 
03-12-2013  2    running  2 
03-10-2013  1    stopped  3 
03-10-2013  3    stopped  4 
03-12-2013  4    running  5 
03-10-2013  5    stopped  6 
03-12-2013  6    running  7 

下面是該查詢到目前爲止,我已經得到了,並且它幾乎是我所需要的:

SELECT entity_header.entityID 
FROM entity_header eh 
INNER JOIN report r on r.entityID = eh.entityID 
WHERE r.startdate between getdate()-7.5 and getdate() 
AND eh.active = 0 
AND eh.location in ('LOCATION1','LOCATION2') 
AND r.status is not null 
AND eh.name is not null 
GROUP BY eh.entityID, r.status, eh.name 
ORDER BY r.status, eh.name; 

我將不勝感激任何建議這個社區可以提供。我會盡我所能提供所需的任何其他信息。

回答

0

這是一個僅在ms SQL上運行的工作示例。

我正在使用rank()來計算entityID出現在結果中的次數。保存爲列表。

該列表將包含實體ID出現次數的整數值。

使用其中a.list = 1,過濾結果。 使用ORDER BY a.ut,a.en,對結果進行排序。 ut和en用於排序。

SELECT a.entityID FROM (
SELECT distinct TOP (100) PERCENT eh.entityID, 
    rank() over(PARTITION BY eh.entityID ORDER BY r.status, eh.name) as list, 
    r.status ut, eh.name en 
FROM report AS r INNER JOIN entity_header as eh ON r.entityID = eh.entityID 
WHERE (r.startdate BETWEEN GETDATE() - 7.5 AND GETDATE()) AND (eh.active = 0) 
AND (eh.location IN ('LOCATION1', 'LOCATION2')) 
ORDER BY r.status, eh.name 
) AS a 
where a.list = 1 
ORDER BY a.ut, a.en 
+0

謝謝院長!這正是我正在尋找的。報告引擎似乎喜歡它,並且一切都在這個世界上再次出現。 – RyanS 2013-03-12 20:53:57

相關問題