结合Count和MIN功能

时间:2017-12-15 14:19:55

标签: sql count min

我的查询部分是:

SUM(POReceiptQuantity)      as Receieved,
MIN(ItemLocalStandardCost)  as Low,
MAX(ItemLocalStandardCost)  as High,

收到的回报是我们今年售出的商品总数。 LOW是我们支付的最低价格,而High是我们支付的最高价格。

我试图合并一个新列,显示我们以低价销售的商品数量。我尝试使用Count和Min函数,但它返回一个"不能对包含聚合或子查询的表达式执行聚合函数"

有没有人有任何想法我怎么能这样做。

谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用当前的GROUP BY查询创建子查询并加入原始表。然后,您可以使用条件COUNT

 SELECT  T2.Received, 
         T2.Low,
         COUNT( CASE WHEN T1.ItemLocalStandardCost = T2.Low THEN 1 END) as Total_Low,
         T2.High,
         COUNT( CASE WHEN T1.ItemLocalStandardCost = T2.High THEN 1 END) as Total_High

 FROM YourTable T1
 CROSS JOIN ( SELECT SUM(Y.POReceiptQuantity)      as Receieved,
                     MIN(Y.ItemLocalStandardCost)  as Low,
                     MAX(Y.ItemLocalStandardCost)  as High
              FROM YourTable Y
              GROUP BY .... ) as T2