基於TSQL group by generate duplicate row代碼,TSQL:爲什麼有些功能產生聚合函數錯誤和其他人不
我不明白爲什麼我可以SUM
,CAST
,以及其他一些功能TSQL沒有 任何錯誤,但MIN和MAX產生一個錯誤:
Failed to execute query. Error: Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
我也試圖改變MIN()
的東西,如:
... WHEN g.dateCreated = (select MIN(dateCreated) from goodies gt where gt.customer_id=g.customer_id) AND ...
但它創造了同樣的錯誤。
那麼,爲什麼我得到這個錯誤的一些功能,我怎麼可以防止它?
with myQuery as (
SELECT
c.name,
c.id,
total_price = sum(case
when g.dateCreated >= '20160601' and g.dateCreated < '20170601'
then cast(g.price as decimal(20,2))
else 0
end),
total_tax = sum(case
when g.dateCreated >= '20160101' and g.dateCreated < '20170101'
then cast(g.tax as decimal(20,2))
else 0
end),
first_cmd = SUM(case
when g.dateCreated = MIN(g.dateCreated) -- Error
then cast(g.command as INTEGER)
else 0
end)
from customers c
left join goodies g
on c.id = g.customer_id
group by
c.name
, c.id
)
select count(*) from myQuery;
謝謝
我會根據dateCreated獲取命令列中的第一個數字。好吧,當我刪除「總和」我需要添加太多的組,並生成重複的行。 –