SQL选择带顺序BY和分组BY的DISTINCT

时间:2018-08-08 09:57:05

标签: sql oracle plsql oracle-sqldeveloper

大家好,我需要查询方面的帮助。 通过下面的select查询,我从左表收到了结果。(请参见下图)。
问题是我需要修改此查询以使结果如右表所示。

SELECT DISTINCT * FROM(
SELECT 
TO_CHAR(D1111MOI__.D1111TFROM + INTERVAL '3' HOUR, 'DD.MM.YYYY HH24:MI') AS TFROM,
TO_CHAR(D1111MOI__.D1111TTILL + INTERVAL '3' HOUR, 'DD.MM.YYYY HH24:MI') AS TTILL,
D1110MOL__.D1110ORDER AS NR,
R0507UNIT_.R0507NAME_ AS NAME,
D1110MOL__.D1110POW__ AS AV

FROM D1110MOL__
INNER JOIN D1109MOH__
ON D1110MOL__.D1109ID___ = D1109MOH__.D1109ID___
AND D1110MOL__.D1110DDAYS = D1109MOH__.D1109DDAYS
INNER JOIN D1111MOI__
ON D1109MOH__.D1109ID___ = D1111MOI__.D1109ID___
AND D1109MOH__.D1109DDAYS = D1111MOI__.D1111DDAYS
INNER JOIN R0507UNIT_
ON D1110MOL__.R0507ID___ = R0507UNIT_.R0507ID___

WHERE (D1111MOI__.D1111TFROM >= TO_DATE('17.05.2017 21:00', 'dd.mm.yyyy hh24:mi')
AND (D1111MOI__.D1111TTILL  <= TO_DATE('18.05.2017 21:00', 'dd.mm.yyyy hh24:mi')))
AND D1109MOH__.D1109TYPE_ = 1
AND D1110MOL__.D1110SEL__ = 1
)
ORDER BY TFROM,NR;

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试使用以下代码:

SELECT TFROM, TTILL, SUM(AV) as TOTAL_AV
  FROM (SELECT DISTINCT TO_CHAR (D1111MOI__.D1111TFROM + INTERVAL '3' HOUR, 'DD.MM.YYYY HH24:MI') AS TFROM,
             TO_CHAR (D1111MOI__.D1111TTILL + INTERVAL '3' HOUR, 'DD.MM.YYYY HH24:MI') AS TTILL,
             D1110MOL__.D1110ORDER AS NR,
             D1110MOL__.D1110POW__ AS AV
        FROM D1110MOL__
             INNER JOIN D1109MOH__ ON D1110MOL__.D1109ID___ = D1109MOH__.D1109ID___ AND D1110MOL__.D1110DDAYS = D1109MOH__.D1109DDAYS
             INNER JOIN D1111MOI__ ON D1109MOH__.D1109ID___ = D1111MOI__.D1109ID___ AND D1109MOH__.D1109DDAYS = D1111MOI__.D1111DDAYS
             INNER JOIN R0507UNIT_ ON D1110MOL__.R0507ID___ = R0507UNIT_.R0507ID___
       WHERE     (    D1111MOI__.D1111TFROM >= TO_DATE ('17.05.2017 21:00', 'dd.mm.yyyy hh24:mi')
                  AND (D1111MOI__.D1111TTILL <= TO_DATE ('18.05.2017 21:00', 'dd.mm.yyyy hh24:mi')))
             AND D1109MOH__.D1109TYPE_ = 1
             AND D1110MOL__.D1110SEL__ = 1)
 GROUP BY TFROM, TTILL
 ORDER BY TFROM;