2017-08-01 52 views
0

基於TSQL group by generate duplicate row代碼,TSQL:爲什麼有些功能產生聚合函數錯誤和其他人不

我不明白爲什麼我可以SUMCAST,以及其他一些功能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; 

謝謝

回答

0

這是導致錯誤的代碼:

first_cmd = SUM(case when g.dateCreated = MIN(g.dateCreated) -- Error 
        then cast(g.command as INTEGER) 
        else 0 
       end) 

你有嵌套在一個SUM()MIN()。這是不允許的。目前還不清楚你想要做什麼,所以很難提出替代方案。如果我不得不猜測。 。 。

select . . . 
     first_cmd = SUM(case when g.dateCreated = mindc -- Error 
          then cast(g.command as INTEGER) 
          else 0 
         end) 
from customers c left join 
    (select g.*, min(g.dateCreated) over (partition by g.customer_id) as mindc 
     from goodies g 
    ) g 
    on c.id = g.customer_id 
. . . 
+0

我會根據dateCreated獲取命令列中的第一個數字。好吧,當我刪除「總和」我需要添加太多的組,並生成重複的行。 –

0

是這樣的嗎?

with firstQuery as (
SELECT c.name, c.id, MIN(g.dateCreated) minDateCreated 
FROM customers c 
LEFT JOIN goodies g 
    on c.id = g.customer_id 
GROUP BY c.name, c.id 
) ,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 = f.minDateCreated 
     then cast(g.command as INTEGER) 
     else 0 
     end) 
from customers c 
    left join goodies g 
    on c.id = g.customer_id 
    left join firstQuery f 
    on f.id = c.id and f.name=c.name 
group by 
    c.name 
    , c.id 
) 
select count(*) from myQuery; 
相關問題