编写查询时遇到了一些困惑:
我是否需要在子查询中声明所有内容以便在最外层的查询中使用?
我正在计算每个高中毕业率(msa_high)组的平均收入,但teradata会一直告知“选定的非聚合值必须是相关组的一部分。”
感谢任何帮助,非常感谢!
SELECT CASE
WHEN subquery.msa_high>=50 AND subquery.msa_high<=60 THEN 'low'
WHEN subquery.msa_high>=60.1 AND subquery.msa_high <=70 THEN 'medium'
WHEN subquery.msa_high>70 THEN 'high'
END AS rate,
SUM(subquery.amt)/COUNT(DISTINCT subquery.saledate) as AvgRevenue
FROM (SELECT s.store, SUM(t.amt)/COUNT(DISTINCT t.saledate), s.msa_high
FROM trnsact t JOIN store_msa s
ON t.store=s.store
WHERE t.stype='P'
AND (t.saledate NOT BETWEEN DATE '2005-08-01' AND LAST_DAY(DATE '2005-08-27'))
HAVING COUNT(DISTINCT t.saledate)>20) as subquery
GROUP BY rate;
准确的查询如下,感谢帮助:
SELECT CASE
WHEN subquery.msa_high>=50 AND subquery.msa_high<=60 THEN 'low'
WHEN subquery.msa_high>=60.1 AND subquery.msa_high <=70 THEN 'medium'
WHEN subquery.msa_high>70 THEN 'high'
END AS rate,
SUM(subquery.amt)/SUM(subquery.saledate) as AvgRevenue
FROM (SELECT s.store, s.msa_high, SUM(t.amt) as amt, COUNT(DISTINCT t.saledate) as saledate
FROM trnsact t JOIN store_msa s
ON t.store=s.store
WHERE t.stype='P'
AND (t.saledate NOT BETWEEN DATE '2005-08-01' AND LAST_DAY(DATE '2005-08-27'))
GROUP BY s.store, s.msa_high
HAVING COUNT(DISTINCT t.saledate)>20) as subquery
GROUP BY rate;
答案 0 :(得分:1)
您必须使用Non-Aggregated
条款中的所有GROUP BY
列。
SELECT CASE
WHEN subquery.msa_high>=50 AND subquery.msa_high<=60 THEN 'low'
WHEN subquery.msa_high>=60.1 AND subquery.msa_high <=70 THEN 'medium'
WHEN subquery.msa_high>70 THEN 'high'
END AS rate,
SUM(subquery.amt)/SUM(subquery.saledate) as AvgRevenue
FROM (SELECT s.store, SUM(t.amt)as amt,COUNT(DISTINCT t.saledate) as saledate, s.msa_high
FROM trnsact t JOIN store_msa s
ON t.store=s.store
WHERE t.stype='P'
AND (t.saledate NOT BETWEEN DATE '2005-08-01' AND LAST_DAY(DATE '2005-08-27'))
GROUP BY s.store, s.msa_high
HAVING COUNT(DISTINCT t.saledate)>20) as subquery
GROUP BY rate;