代码之家  ›  专栏  ›  技术社区  ›  ryvantage

包括结果但不包括SQL查询中的数据

  •  1
  • ryvantage  · 技术社区  · 6 年前

    我有一张桌子(甲骨文):

    customer_quote
    ------
    int id
    int part_key (fk)
    int condition_code (fk)
    number unit_price
    int qty_quoted
    date entry_date
    

    通过查询选择上一年的数据:

    SELECT cq.part_key 
        , cq.condition_code 
        , COUNT(*) AS cq_count 
        , SUM(cq.unit_price * cq.qty_quoted) AS cq_total 
        , SUM(cq.qty_quoted) cq_qty
    FROM customer_quote cq 
    WHERE cq.entry_date > TO_DATE('09-Jun-2017', 'dd-mm-yyyy')
    GROUP BY cq.part_key 
        , cq.condition_code 
    

    但是我需要这些数据包括过去两年的活动部分,但是超过1年的数据不应该计算到总数中。因此,去年没有数据的部分应该在结果中显示,但是 0, 0, 0 对于总计,如下所示:

    44814   45  25  20114.1 81
    41404   45  4   10237   50
    31823   45  4   1050.5  17
    25380   49  0   (null)  (null)
    58791   46  0   (null)  (null)
    13012   45  0   (null)  (null)
    

    我怎样才能做到这一点?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andomar    6 年前

    case sum

    SUM(CASE WHEN cq.entry_date > add_months(sysdate, -12)
             THEN cq.unit_price * cq.qty_quoted END) AS cq_total 
    

    when else null