TSQL查询汇总数据

时间:2019-02-08 00:37:48

标签: sql sql-server tsql

我有一个查询,返回两种不同产品的最小值,最大值,平均值和总计。但是,客户需要两种产品的最小值,最大值,平均和总计。但是,当我尝试对两个乘积求和并尝试合计日期时,返回了不希望的结果。

以下SQL查询返回两种产品的单独数据:

SELECT 
   CONVERT(date, DateTimeNow) AS Date,
   MIN(FT1) AS Minimum1 , 
   MAX(FT1) AS Maximum1, 
   AVG(FT1) AS Average1, 
   MAX(FQ1) AS Total1,
   MIN(FT2) AS Minimum2, 
   MAX(FT2) AS Maximum2, 
   AVG(FT2) AS Average2, 
   MAX(FQ2) AS Total2
FROM Data
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);

然后我将查询修改为以下内容:

SELECT 
    CONVERT(date, DateTimeNow) AS Date,
    MIN(FT1+FT2) AS Minimum , 
    MAX(FT1+FT2) AS Maximum, 
    AVG(FT1+FT2) AS Average, 
    MAX(FQ1+FT2) AS Total
FROM Data
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);

但是,当我运行第二个查询时,结果不累加。例如,Minimum不会加到第一个查询中Minimum1 + Minimum2

4 个答案:

答案 0 :(得分:1)

我了解您将每种产品存储在同一表的不同列中。计算最小,平均和最大值的组合的逻辑可能如下:

SELECT 
    CONVERT(date, DateTimeNow) AS Date,
    CASE WHEN MIN(FT1) < MIN(FT2) THEN MIN(FT1) ELSE MIN(FT2) END AS Minimum, 
    CASE WHEN MAX(FT1) > MAX(FT2) THEN MAX(FT1) ELSE MAX(FT2) END AS Maximum, 
    ( AVG(FT1) + AVG(FT2) ) / 2 AS Average,
    SUM(FT1) + SUM(FT2) AS Total
FROM Data
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);

含义:

  • minimum是产品1的最小值与产品2的最小值之间的最小值
  • maximum是产品1的最大值与产品2的最大值之间的最大值
  • 平均值是产品1的平均值和产品2的平均值
  • 总计是两个查询的总和

您可以根据需要(未完全指定)调整这些规则。

答案 1 :(得分:1)

感谢大家的投入。以下是我执行的正确查询:

SELECT 
    CONVERT(date, DateTimeNow) AS Date, MIN(FT1) + MIN(FT2) AS Minimum, 
    MAX(FT1) + MAX(FT2) AS Maximum,
    AVG(FT1) + AVG(FT2) / 2 AS Average,
    MAX(FQ1) + MAX(FQ2) AS Total1
FROM #rawData
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);

答案 2 :(得分:1)

我强烈建议:

SELECT CONVERT(date, DateTimeNow) AS Date,
       MIN(v.FT) AS Minimum , 
       MAX(v.FT) AS Maximum, 
       AVG(v.FT) AS Average, 
       MAX(v.FQ1) AS Total
FROM Data CROSS APPLY
     (VALUES (FT1, FQ1), (FT2, FQ2)) as v(FT, FQ)
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);

尤其是,这应该正确处理NULL值。两个值的平均值不一定是两个值的平均值。

答案 3 :(得分:0)

“ FROM”子句通过添加您要对其执行操作的两个记录来进行添加。您的日期逻辑没有做任何事情-它会获取所有日期的所有记录,然后“错误地”始终放置今天的日期。

SELECT CONVERT(date, DateTimeNow) AS Date, MIN(FT) AS Minimum , MAX(FT) AS Maximum, AVG(FT) AS Average, SUM(FT) AS Total, COUNT(FT) as NumOfRecs
FROM Data
WHERE ProductName IN ('FTName1','FTName2')
GROUP BY CONVERT(date, DateTimeNow)
ORDER BY CONVERT(date, DateTimeNow);