需要SUM,AVG,COUNT个结果仅按月份和年份分组

时间:2017-12-27 16:34:52

标签: sql-server tsql window-functions

我试图通过下面提到的查询从销售数据中获得每年每个月的销售额,销售额,平均销售价格,市场中位数和中位数销售价格的美元总和:

SELECT CAST(MNTH AS VARCHAR(2)) +'-'+ CAST(YR AS VARCHAR(4)) AS 'MONTH-YEAR', YR, MNTH, 
    MAX(dol_vol) AS 'Dol. Vol.',
    MAX(no_sales) AS '# of Sales',
    MAX(avg_price) AS 'Average Price',
    MAX(med_price) AS 'Median Price',
    MAX(med_days) AS 'Median Days'
FROM (SELECT YEAR(dt) YR, MONTH(dt) MNTH,
    SUM(sale_price) dol_vol,
    COUNT(sale_price) no_sales,
    AVG(sale_price) avg_price,
    PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY sale_price) OVER (PARTITION BY year(dt), month(dt)) med_price,
    PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY days_mkt) OVER (PARTITION BY year(dt), month(dt)) med_days
  FROM Sales_Data
  WHERE status='sld' AND year(dt)>='2000' AND sale_price>1000) d
GROUP BY YR, MNTH
ORDER BY YR, MNTH;

但是,我收到了下面提到的错误:

Msg 8120, Level 16, State 1, Line 7
Column 'Sales_Data.dt' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

现在,如果我尝试在子查询中为'dt'列添加GROUP BY条件,我也会得到sale_price和days_mkt列的相同错误。我如何获得资源

1 个答案:

答案 0 :(得分:1)

试试这个:

    SELECT CAST(MNTH AS VARCHAR(2)) +'-'+ CAST(YR AS VARCHAR(4)) AS 'MONTH-YEAR', YR, MNTH, 
    MAX(dol_vol) AS 'Dol. Vol.',
    MAX(no_sales) AS '# of Sales',
    MAX(avg_price) AS 'Average Price',
    MAX(med_price) AS 'Median Price',
    MAX(med_days) AS 'Median Days'
FROM 
(
    SELECT YEAR(dt) YR, MONTH(dt) MNTH,
    NULL dol_vol,
    NULL no_sales,
    NULL avg_price,
    PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY sale_price) OVER (PARTITION BY year(dt), month(dt)) med_price,
    PERCENTILE_CONT(.50) WITHIN GROUP (ORDER BY days_mkt) OVER (PARTITION BY year(dt), month(dt)) med_days
    FROM Sales_Data
    WHERE status='sld' AND year(dt)>='2000' AND sale_price>1000

    UNION ALL

    SELECT YEAR(dt) YR, MONTH(dt) MNTH,
    SUM(sale_price) dol_vol,
    COUNT(sale_price) no_sales,
    AVG(sale_price) avg_price,
    NULL,
    NULL
    FROM Sales_Data
    WHERE status='sld' AND year(dt)>='2000' AND sale_price>1000
    GROUP BY  YEAR(dt)
             ,MONTH(dt) 

) d
GROUP BY YR, MNTH
ORDER BY YR, MNTH;

在内部查询中,我们需要准确地告诉引擎哪些列/值要分组。