SQL SUM之间的两个计数结果

时间:2017-01-24 09:25:42

标签: sql-server

function Main() {}

Main.prototype = Object.assign(Submain.prototype, {
    doThat: function() {
        Submain.call(this);
        //from here I can use this.a, this.b, this.c, this.d
    },
    //...Main functions...
});

function Submain() {
   this.a = 1;
   this.b = 2;

   //this works now
   this.doThis();
}

Submain.prototype.doThis = function() {
   this.c = 3;
   this.d = 4;
}

这是正确的方式来SELECT [Soldtopt], [tradingname], [DlvDate], SUM(try_cast(Netvalue as float)) as Netvalue, count(distinct SDDoc) as Salesdoc , count(distinct case when Netvalue = '0' then 1 else null end) as ZeroValue , sum (count(distinct SDDoc)) , (count(distinct case when Netvalue = '0' then 1 else null end)) As result FROM [FOC].[dbo].[foc] GROUP by Soldtopt,tradingname,DlvDate ORDER BY count (distinct SDDoc) DESC; ?或者我收到错误"

  

Msg 130,Level 15,State 1,Line 13   无法对包含聚合或子查询的表达式执行聚合函数。"   [在此输入图像说明] [1]

[1]:https://i.stack.imgur.com/u1LGz.jpg嗨这个结果应该像2,2,0,1,结果显示像35,35,35,35

3 个答案:

答案 0 :(得分:0)

ORDER BY  count (distinct SDDoc) DESC;

这将根据col的数量对数据进行排序,col的索引是count函数返回的值。

sum (count(distinct SDDoc)) 

这不是一个有效的陈述。

 count(distinct case when  Netvalue = '0' then 1 else null end)

此外,请尝试在此计数中使用子查询。

答案 1 :(得分:0)

使用SUM OVER()

SELECT [Soldtopt],
       [tradingname],
       [DlvDate],
       Sum(try_cast(Netvalue as float)) AS Netvalue,
       Count(DISTINCT SDDoc)   AS Salesdoc,
       Count(DISTINCT CASE WHEN Netvalue = '0' THEN 1 ELSE NULL END) AS ZeroValue, -- will always return 1
       Sum (Count(DISTINCT SDDoc))OVER(),
       Count(DISTINCT CASE WHEN Netvalue = '0' THEN 1 ELSE NULL END) AS result -- will always return 1
FROM   [FOC].[dbo].[foc]
GROUP  BY Soldtopt,
          tradingname,
          DlvDate
ORDER  BY Count (DISTINCT SDDoc) DESC; 

Count聚合也将始终返回1

Count(DISTINCT CASE WHEN Netvalue = '0' THEN 1 ELSE NULL END) 

添加样本数据和预期结果可以解决查询中的逻辑错误

答案 2 :(得分:0)

solve.count(distinct SDDoc) - count(当Netvalue ='0'然后1 else null结束时的不同情况)作为结果