具有相同分组依据的SQL子查询选择

时间:2018-06-21 14:00:28

标签: sql db2 subquery

我认为这是不可能的,但是我希望有一种我不知道的方法。我目前有这个查询:

SELECT month(app.created) AS Month, year(app.created) AS Year, count(*) AS Total, 
    (SELECT month(app.created) AS Month, year(app.created) AS Year, count(*) AS Total
    FROM lwmod10ht/oaapappl AS app
    INNER JOIN lwmod10ht/oaapposi AS pos
    ON pos.username = app.username
    WHERE pos.jobclass IS NOT NULL AND pos.requisition IS NULL
    GROUP BY month(app.created), year(app.created) 
    ORDER BY year(app.created) asc, month(app.created) asc) AS Direct_Count
FROM lwmod10ht/oaapappl AS app
GROUP BY month(app.created), year(app.created), Direct_Count
ORDER BY year(app.created) asc, month(app.created) asc

其目的是获取给定时间段内的申请数量并将其按月/年分组。然后,Direct_Count列试图将总计数分解为一个子类别。

因此,理想的结果是月,年,总数,直接数。现在,我知道您不能在子查询中返回多个列,但是由于我的group by列是相同的,因此我想必须要有一种方法可以匹配这些值?还是只需要运行两个完全独立的查询?

2 个答案:

答案 0 :(得分:1)

由于两个查询的过滤条件不同(它们选择不同的行),因此您需要两个查询。

但是,我会将它们放在from子句中(而不是使用标量子查询),并将它们加入那里,从而使我可以灵活选择要选择的列。例如:

select x.*, y.direct_count
  from (
    SELECT 
        month(app.created) AS Month,
        year(app.created) AS Year,
        count(*) AS Total
      FROM lwmod10ht/oaapappl AS app
      GROUP BY month(app.created), year(app.created)
      ORDER BY year(app.created) asc, month(app.created) asc
    ) x left join (
    SELECT 
        month(app.created) AS Month, 
        year(app.created) AS Year, 
        count(*) AS direct_count
      FROM lwmod10ht/oaapappl AS app
      JOIN lwmod10ht/oaapposi AS pos ON pos.username = app.username
      WHERE pos.jobclass IS NOT NULL AND pos.requisition IS NULL
      GROUP BY month(app.created), year(app.created) 
      ORDER BY year(app.created) asc, month(app.created) asc
    ) y on x.year = y.year and x.month = y.month;

答案 1 :(得分:1)

为同一问题添加一些更简洁的解决方案:

1。使用FILTER(警告:它不起作用)

如果DB2实现了新的标准SQL:2003 FILTER子句,则可以编写如下内容:

SELECT 
    month(app.created) AS Month,
    year(app.created) AS Year,
    count(*) AS Total,
    count(*) FILTER (
      WHERE pos.jobclass IS NOT NULL AND pos.requisition IS NULL
      ) AS direct_count
  FROM lwmod10ht/oaapappl AS app
  GROUP BY month(app.created), year(app.created)
  ORDER BY year(app.created) asc, month(app.created) asc;

但这只是一厢情愿。

2。可怜的人的过滤器(效果很好,速度更快)

此解决方案只运行一次数据,因此比接受的答案要快。这种解决方案通常被称为“穷人的过滤器”:

SELECT 
    month(app.created) AS Month,
    year(app.created) AS Year,
    count(*) AS Total,
    sum(CASE
      WHEN pos.jobclass IS NOT NULL AND pos.requisition IS NULL THEN 1
      ELSE 0
      END) AS direct_count
  FROM lwmod10ht/oaapappl AS app
  GROUP BY month(app.created), year(app.created)
  ORDER BY year(app.created) asc, month(app.created) asc;