SQL 在子查询中分组

SQL group by in Subquery

在将 unix 列转换为常规时间戳后,我正在尝试使用 group by 获取月度生产。你能告诉我如何在代码中使用group by吗?

'''

With production(SystemId, dayof, monthof, yearof, powerwatts, productionwattshours) as 
(
Select   SystemId,
            [dayof] = DAY(hrdtc), 
            [monthof] = MONTH(hrdtc),
            [yearof] = YEAR(hrdtc),
        powerwatts, productionwatthours
    from (
    Select  * , dateadd(s, UnixTime, '19700101') as hrdtc from meterreading ) ds
    )

    Select * from production
    where systemId = 2368252 

'''

我认为您正在寻找这个(从技术上讲您不需要子查询,但它可以让您避免重复 DATEADD() 表达式):

SELECT SystemId = 2368252,
  [Month] = DATEFROMPARTS(YEAR(hrdtc), MONTH(hrdtc), 1),
  powerwatts = SUM(powerwatts),
  productionwatthours = SUM(productionwatthours)
FROM
(
  SELECT powerwatts, productionwatthours,
    DATEADD(SECOND, UnixTime, '19700101') as hrdtc
  FROM dbo.enphasemeterreading
  WHERE systemId = 2368252 
) AS ds 
GROUP BY DATEFROMPARTS(YEAR(hrdtc), MONTH(hrdtc), 1);

如果您还想避免重复 GROUP BY 表达式:

SELECT SystemId = 2368252,
  [Month],
  powerwatts = SUM(powerwatts),
  productionwatthours = SUM(productionwatthours)
FROM
(
  SELECT [Month] = DATEFROMPARTS(YEAR(hrdtc), MONTH(hrdtc), 1),
    powerwatts, productionwatthours
  FROM
  (
    SELECT powerwatts, productionwatthours,
      DATEADD(SECOND, UnixTime, '19700101') as hrdtc
    FROM dbo.enphasemeterreading
    WHERE systemId = 2368252 
  ) AS ds1
) AS ds2 
GROUP BY [Month];

就我个人而言,我不认为这更漂亮或更清晰。其他一些提示:

更新要求(请预先说明):我如何将此查询加入另一个table?

SELECT * FROM dbo.SomeOtherTable AS sot
INNER JOIN
(
  SELECT SystemId = 2368252,
    [Month],
    powerwatts = SUM(powerwatts),
    productionwatthours = SUM(productionwatthours)
  FROM
  ...
  GROUP BY [Month]
) AS agg
ON sot.SystemId = agg.SystemId;