数据透视表中的平均计数数据 - 需要帮助

时间:2016-10-22 14:39:42

标签: sql sql-server tsql

我正在开发一个小项目来提供从数据库中提取数据的应用程序,以显示每周每天发货的平均值。我已经取得了一些进展,现在有了计算所有出货量的脚本,但由于我根据varchar类型的列计算它们,我还需要解决方案来分别计算每周每天的平均值。

到目前为止,我最终得到的结论如下:

SELECT [Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday]
    FROM (
        SELECT DATENAME(dw, Shipment.Date) AS DayWeek, Shipment.ID
        FROM Shipment
        WHERE  MONTH(Shipment.Date)= MONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, 'OCTOBER 2016' ), 0)) AND
        Shipment.Bur = 'GB'
) AS src
pivot (
    COUNT(ID) FOR DayWeek IN ([Monday], [Tuesday], [Wednesday], [Thursday], [Friday], [Saturday], [Sunday])
 ) AS pvt

我非常感谢任何提示或帮助,因为看起来我现在已经没有想法,可以进一步提供正确的解决方案。

2 个答案:

答案 0 :(得分:0)

我建议完全取消pivot并将结果放在不同的行中:

SELECT DayWeek, AVG(cnt) 
FROM (SELECT s.Date, DATENAME(dw, s.Date) AS DayWeek, COUNT(*) as cnt
      FROM Shipment s
      WHERE MONTH(s.Date) = MONTH(DATEADD(MONTH, DATEDIFF(MONTH, 0, 'OCTOBER 2016' ), 0)) AND
            s.Bur = 'GB'
      GROUP BY s.Date
     ) d
GROUP BY DayWeek
ORDER BY MIN(s.Date);

答案 1 :(得分:0)

通过浏览stackoverflow遇到其中一个用户发布的类似问题,我找到了我的问题的答案。

    SELECT [Day], SUM(q.Totals) AS "Weekly Shipment Amount", AVG(Totals) AS [Avg]
FROM
(
    SELECT 
  w = DATEDIFF(WEEK, 0, DATE),
      [Day]  = DATENAME(Weekday, DATE),
      Totals = COUNT(*)
    FROM dbo.Shipment
    --INNER JOIN FCLI (NOLOCK) ON FCLI.CCLI = FEXP.CCLI 
      WHERE (BUR = 'GB' AND
      Shipment.Date >= '20160601' AND Shipment.Date <= '20160630')

    GROUP BY 
        DATEDIFF(WEEK, 0, Date),
        DATENAME(WEEKDAY, Date),
        DATEPART(WEEKDAY, Date)
  ) AS q
GROUP BY [Day]
ORDER BY [DaY] ASC;