用于组合行的SQL查询

时间:2018-04-14 15:13:13

标签: sql

我有一个查询,目前打印出我需要的内容,但没有合并我需要的行。例如,我需要将前两行与仪表名称组合在一起,依此类推其他仪表名称。

这是我目前所拥有的:

SELECT      
    --Displays Client Number
    CASE
        WHEN v.MID IS NULL THEN ''
        ELSE v.ClientNumber
    END AS 'Client Number',

    --Displays MID Number
    CASE
        WHEN v.MID IS NULL THEN ''
        ELSE v.MID
    END AS MID,

    --Displays Meter Name
    CASE
        WHEN v.MID IS NULL THEN ''
        ELSE v.MeterName
    END AS 'Meter Name',
    /*
    CASE
        WHEN v.MID IS NULL THEN 0
        ELSE SUM(v.MCF)
    END AS MCF,
    */


    --Displays January's MCF
    CASE
        WHEN v.AccountPeriod = '2018-01-01' THEN SUM(v.MCF)
        ELSE 0
    END AS January,

    --Displays Febuary's MCF
    CASE
        WHEN v.AccountPeriod = '2018-02-01' THEN SUM(v.MCF)
        ELSE 0
    END AS Febuary,


    CASE
        WHEN v.MID IS NULL THEN 0
        ELSE SUM(v.mcf)
    END AS 'Meter Total'

FROM Volumes v
LEFT JOIN CurrentMeters cm 
    ON v.MID = cm.MID
WHERE cm.ClientNumber = 107500
GROUP BY v.MID, v.AccountPeriod, v.ClientNumber, v

有没有人对我应该做什么或如何处理这个问题有任何建议?

1 个答案:

答案 0 :(得分:1)

我认为你只想要条件聚合:

SELECT (CASE WHEN v.MID IS NULL THEN '' ELSE v.ClientNumber END) AS Client_Number,
       COALESCE(WHEN v.MID, '') as MID,
       (CASE WHEN v.MID IS NULL THEN '' ELSE v.MeterName END) AS Meter_Name,
      SUM((CASE WHEN v.MID IS NULL THEN 0 v.MCF END) AS MCF,
      SUM(CASE WHEN v.AccountPeriod = '2018-01-01' THEN v.MCF ELSE 0 END) AS January,
      SUM(CASE WHEN v.AccountPeriod = '2018-02-01' THEN v.MCF ELSE 0 END) AS January,
      SUM(CASE WHEN v.MID IS NULL THEN 0 ELSE v.mcf END) AS Meter_Total
FROM Volumes v JOIN
     CurrentMeters cm 
     ON v.MID = cm.MID
WHERE cm.ClientNumber = 107500
GROUP BY (CASE WHEN v.MID IS NULL THEN '' ELSE v.ClientNumber END),
         COALESCE(WHEN v.MID, ''),
        (CASE WHEN v.MID IS NULL THEN '' ELSE v.MeterName END);

注意:

  • 您的WHERE子句正在将外部联接转换为内部联接,因此没有理由表达外部联接。
  • GROUP BY键指定在结果集中定义行的内容。数据中每个唯一值的组合恰好是一行。因此,您不希望AccountPeriod中有GROUP BY
  • 据推测,您希望每个定义行的表达式都有一行,因此这些表达式位于group by
  • 对于条件聚合,CASE表达式是聚合函数的参数,例如SUM()