TSQL:为什么某些函数会产生聚合函数错误,而其他函数则不会

时间:2017-08-01 15:52:22

标签: sql sql-server tsql stored-procedures aggregate-functions

基于TSQL group by generate duplicate row代码,

我不明白为什么我可以制作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;

谢谢

2 个答案:

答案 0 :(得分:0)

这是导致错误的代码:

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

MIN()嵌套了SUM()。这是不允许的。目前还不清楚你想做什么,所以很难提出替代方案。

如果我不得不猜。 。 。

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
. . .

答案 1 :(得分: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;