带有GROUP BY中非聚合字段的Teradata SQL

时间:2016-10-30 15:47:59

标签: mysql sql teradata

我有下面的代码,Teradata不起作用,并将消息返回为“选定的非聚合值必须是关联组的一部分”。我想我已经确保所有非聚合字段已经放入GROUP BY子句中。你能帮我看看它为什么不起作用吗?

SELECT  str.store,str.city, str.state, dep.deptdesc, 100*(Clean.DecSales/Clean.DecSaleDays-Clean.NovSales/Clean.NovSaleDays)/(Clean.NovSales/Clean.NovSaleDays) AS PercentageChange

FROM ((skuinfo sku LEFT JOIN deptinfo dep ON sku.dept=dep.dept)

LEFT JOIN 
(SELECT t.sku, t.store, COUNT(DISTINCT t.saledate) AS NumOfDays, SUM(t.amt) AS DailyTotal,

(CAST(EXTRACT(YEAR FROM t.saledate) AS VARCHAR(8)))||'.'||
      (CAST(EXTRACT(MONTH FROM t.saledate) AS VARCHAR(8)))||'.'||
      (CAST(t.store AS VARCHAR(8)))AS ComboID,

SUM(CASE WHEN EXTRACT(MONTH from t.saledate) =11 THEN t.Amt END) AS NovSales,

SUM(CASE WHEN EXTRACT(MONTH from t.saledate) =12 THEN t.Amt END) AS DecSales,

COUNT(CASE WHEN EXTRACT(MONTH from t.saledate) =11 THEN t.saledate END) AS NovSaleDays,

COUNT(CASE WHEN EXTRACT(MONTH from t.saledate) =12 THEN t.saledate END) AS DecSaleDays

FROM trnsact t

WHERE (t.saledate NOT BETWEEN '2005-08-01' AND '2005-08-31') AND t.stype='P'

GROUP BY t.sku, t.store

HAVING NumOfDays>19) Clean 

ON sku.sku=Clean.sku)

LEFT JOIN strinfo str ON str.store=Clean.store

GROUP BY str.store,str.city, str.state, dep.deptdesc;

2 个答案:

答案 0 :(得分:1)

这是您的SELECT

SELECT str.store, str.city, str.state, dep.deptdesc,
       (100*(Clean.DecSales/Clean.DecSaleDays-Clean.NovSales/Clean.NovSaleDays)/(Clean.NovSales/Clean.NovSaleDays) ) AS PercentageChange

这是您的GROUP BY

GROUP BY str.store, str.city, str.state, dep.deptdesc

我在SELECT中看到很多列引用不在GROUP BY中。我猜你打算SELECT这样:

SELECT str.store, str.city, str.state, dep.deptdesc,
       SUM(100*(Clean.DecSales/Clean.DecSaleDays-Clean.NovSales/Clean.NovSaleDays)/(Clean.NovSales/Clean.NovSaleDays)
          ) AS PercentageChange

外部查询中根本没有GROUP BY

答案 1 :(得分:0)

删除外部查询的GROUP BY。将派生表GROUP BY中的Clean替换为序号GROUP BY 1, 2, 5

有些东西让我相信派生表的列ComboID,由SaleDateStoreID组成,因为SaleDate不是GROUP BY的一部分,而是在其他地方参与在派生表的聚合中。