SQL:GROUP BY子句

时间:2015-06-30 16:28:25

标签: sql sql-server

SELECT
    (1.0*( SELECT SUM(r.SalesVolume)
           FROM
               RawData r
               INNER JOIN Product p
                   ON r.ProductId = p.ProductId
           WHERE p.Distributor in ('TF1','WARNER')
           GROUP BY p.Distributor
         )
         /
         ( SELECT SUM(r.SalesVolume)
           FROM RawData r
         )*100)
    ;

上述查询导致错误:

  

查找错误 - SQL Server数据库错误:子查询返回的值超过1。当子查询遵循=,!=,<,< =,>,> =或子查询用作表达式时,不允许这样做。

GROUP BY子句的问题是什么?不确定如何解决这个问题。

3 个答案:

答案 0 :(得分:4)

您的查询的这一部分是问题:

SELECT SUM(r.SalesVolume) FROM RawData r
INNER JOIN Product p
ON r.ProductId = p.ProductId
WHERE p.Distributor in ('TF1','WARNER') GROUP BY p.Distributor
                                        ^^^^^^^^^^^^^^^^^^^^^^

您正在通过p.Distributor进行分组,并且可能有两个基于您的where子句。 WHERE p.Distributor in ('TF1','WARNER')。您可以逐出群组,SUMTF1

总共WARNER
SELECT
(1.0 * (SELECT SUM(r.SalesVolume) FROM RawData r
        INNER JOIN Product p ON r.ProductId = p.ProductId
        WHERE p.Distributor in ('TF1','WARNER')
) / (SELECT SUM(r.SalesVolume) FROM RawData r)*100);

如果您想通过分销商获得销售量的百分比,则应使用此代替。

SELECT p.Distributor, SUM(r.SalesVolume) as Sales, ROUND((SUM(r.SalesVolume) / (SELECT SUM(r.SalesVolume) FROM RawData r) * 100), 1) as percentOfTotal
FROM RawData r
INNER JOIN Product p ON r.ProductId = p.ProductId
WHERE p.Distributor in ('TF1','WARNER')
GROUP BY p.Distributor

我建议在这里使用ROUND function。上述查询将舍入到小数点后的单个数字。如果你想要两位数,请使用:

ROUND((SUM(r.SalesVolume) / (SELECT SUM(r.SalesVolume) FROM RawData r) * 100), 2) as percentOfTotal

答案 1 :(得分:0)

您的相关查询:

SELECT SUM(r.SalesVolume) 
FROM RawData r
INNER JOIN Product p
    ON r.ProductId = p.ProductId
WHERE p.Distributor in ('TF1','WARNER')
GROUP BY p.Distributor)

将为每个组返回一行,即一个用于TF1,一个用于WARNER。

您不需要按任何会导致多行的字段进行分组

答案 2 :(得分:0)

SELECT  COALESCE(SUM(CASE WHEN p.distributor IN ('TF1', 'WARNER') THEN rawData END), 0) * 100.0 / SUM(rawData)
FROM    rawData r
LEFT JOIN
        product p
USING   (productId)