1

我正在尝试创建一个查询,该查询返回特定实体记录的列表,而不从 entityID 字段返回任何重复的条目。该查询无法使用DISTINCT,因为该列表正在传递给一个报告引擎,该引擎不理解包含多于 entityID 的结果集,并且DISTINCT需要返回所有ORDER BY字段。

结果集不能包含重复的 entityID,因为报告引擎也不能在同一运行中两次处理同一实体的报告。我发现临时表也不支持的困难方式。

需要在查询中对条目进行排序,因为报表引擎只允许在 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;

我将不胜感激这个社区可以提供的任何建议。我将尽我所能提供所需的任何其他信息。

4

1 回答 1

0

这是一个仅在 ms SQL 上运行的工作示例。

我正在使用 rank() 来计算 entityID 在结果中出现的次数。保存为列表。

该列表将包含 entityID 出现次数的整数值。

使用where 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
于 2013-03-12T20:51:05.433 回答