需要SUM,AVG,COUNT of results GROUPED BY month and year only
我正在尝试获得销售额,销售计数,平均销售价格,市场中位数和每个月的中间销售价格从销售数据年通过下文提到的查询:需要SUM,AVG,COUNT of results GROUPED BY month and year only
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.
现在,如果我尝试添加GROUP BY条件“DT”列在子查询中,我也为sale_price和days_mkt列获得相同的错误。如何获取资源
回答:
试试这个:
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;
在我们需要确切地告诉引擎由列/值由组内查询。
以上是 需要SUM,AVG,COUNT of results GROUPED BY month and year only 的全部内容, 来源链接: utcz.com/qa/266354.html