从选择子查询里面选择一列?

时间:2018-10-04 08:19:27

标签: sql

如何从子查询到父查询中选择Attr1?我尝试使用Average.Attr1,但不起作用。

  

不是单组分组功能

SELECT SUM(Report.Attr1), 
       SUM(Report.Attr2), 
       SUM(Report.Attr3), 
       0
FROM {Report}, 
(
    SELECT AVG(Report.Attr1),
           AVG(Report.Attr2),
           AVG(Report.Attr3)
    FROM Report
    WHERE 
        StartDate <= Report.Date AND
        Report.Date <= EndDate
    GROUP BY Report.Attr1, Report.Attr2, Report.Attr3
) Average
WHERE 
    StartDate <= Report.Date AND
    Report.Date <= EndDate

3 个答案:

答案 0 :(得分:1)

您可以为这些聚合函数添加别名,以便可以在外部查询中使用它们

var querydb = `INSERT INTO msg_conversations VALUES (DEFAULT, ${user_id}, null, null, null, null, ('{"key": "value", "unique": "' || uuid_generate_v4() || '"}'::TEXT)::jsonb, to_timestamp('05 Dec 2000', 'DD Mon YYYY'), to_timestamp('05 Dec 2000', 'DD Mon YYYY') )`

或者,如果您只想限制它们,则可以将HAVING子句与GROUP BY一起使用

SELECT SUM(avg_attr1), 
       SUM(avg_attr2), 
       SUM(avg_attr3), 
       0
FROM {Report}, 
(
    SELECT AVG(Report.Attr1) as avg_attr1,
           AVG(Report.Attr2) as avg_attr2,
           AVG(Report.Attr3) as avg_attr3
    ...

答案 1 :(得分:0)

我不确定这是否是您想要的,但是我可以通过以下方式使它起作用:

WITH REPORT (STARTDATE,ENDDATE,DATE1,ATTR1,ATTR2,ATTR3)AS(
SELECT DATE '2018-01-01',DATE '2018-02-01',DATE '2018-01-11', 1,2,3 FROM DUAL UNION ALL
SELECT DATE '2018-01-01',DATE '2018-02-01',DATE '2018-01-11',1,2,3 FROM DUAL UNION ALL
select date '2018-01-01',DATE '2018-02-01',DATE '2018-01-11',1,2,3 from dual 
)

SELECT SUM(Report.Attr1), 
       SUM(Report.Attr2), 
       SUM(REPORT.ATTR3), 
       0,
       average.a,average.b,average.c
FROM REPORT, 
(
    SELECT AVG(REPORT.ATTR1) A,
           AVG(REPORT.ATTR2) B ,
           AVG(Report.Attr3) c
    FROM Report
    WHERE 
        STARTDATE <= REPORT.DATE1 AND
        Report.Date1 <= EndDate
    GROUP BY Report.Attr1, Report.Attr2, Report.Attr3
) Average
WHERE 
    STARTDATE <= REPORT.DATE1 AND
    REPORT.DATE1 <= ENDDATE
    GROUP BY 0,
       average.a,average.b,average.c

答案 2 :(得分:0)

您可以通过提供别名来引用它们。现在,如果您说Average.attr,您将获得与Report.Attr1

相对应的值
SELECT SUM(Report.Attr1), 
           SUM(Report.Attr2), 
           SUM(Report.Attr3), 
           0,
           Average.attr
    FROM {Report}, 
    (
        SELECT AVG(Report.Attr1) as attr,
               AVG(Report.Attr2),
               AVG(Report.Attr3)
        FROM Report
        WHERE 
            StartDate <= Report.Date AND
            Report.Date <= EndDate
        GROUP BY Report.Attr1, Report.Attr2, Report.Attr3
    ) Average
    WHERE 
        StartDate <= Report.Date AND
        Report.Date <= EndDate