2

在 MS Sql 中。

SELECT a.SellerID, 
       SUM(TransactionFee) as TransactionFees,
SUM(Quantity*a.PriceItem) as TransactionValue,
COUNT(*) as OrdersWithTransactionFees, 
            SUM(Quantity) as Qty,
            (SELECT SUM(a.Quantity*a.PriceItem) as WholeMonthTransactionValue 
            from BuyProductDetails where SellerID = a.SellerID) as aa
FROM BuyProductDetails as a
WHERE MONTH(a.OrderDate)=3
AND YEAR(a.OrderDate)=2013
AND TransactionFee IS NOT NULL
GROUP BY a.SellerID

我有上面的查询......它似乎无法运行。

基本上,我有这张表BuyProductDetails存储来自不同卖家的所有订单。

有些订单会有 TransactionFee。

现在,我需要计算这些带有 TransactionFee 的订单的总销售额,以及这些卖家的总销售额,包括那些没有 TransactionFee 的订单。

结果集应具有以下字段:

  1. 卖家ID
  2. 交易费用总额
  3. 总销售额
  4. 有交易费的订单数量
  5. 订购数量
  6. 该卖家的总销售额

但是当我运行这个 sql 时,它返回以下错误:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

任何帮助深表感谢。谢谢你。

4

2 回答 2

0

尝试过这样的事情吗?

 SELECT a.SellerID, 
    SUM(TransactionFee) as TransactionFees,
    SUM(Quantity*a.PriceItem) as TransactionValue,
    COUNT(*) as OrdersWithTransactionFees, 
    SUM(Quantity) as Qty,
    MIN(a.WholeMonthTransactionValue) as WholeMonthTransactionValue
  FROM BuyProductDetails as a,
(SELECT b.SellerID, 
        SUM(b.Quantity*b.PriceItem) as WholeMonthTransactionValue,
        MONTH(b.OrderDate),
        YEAR(b.OrderDate)
 FROM BuyProductDetails b 
 GROUP BY b.SellerID,
    MONTH(b.OrderDate) as MonthID,
    YEAR(b.OrderDate) as YearID) as aa
    WHERE MONTH(a.OrderDate)=3
      AND YEAR(a.OrderDate)=2013
      AND TransactionFee IS NOT NULL
      AND a.SellerID = aa.SellerID
      AND MONTH(a.OrderDate)=aa.MonthID
      AND YEAR(a.OrderDate) = aa.YearID
    GROUP BY a.SellerID)
于 2013-03-14T07:02:46.933 回答
0

您可以在CASE表达式中使用更有效的选项

SELECT a.SellerID, 
       SUM(CASE WHEN TransactionFee IS NOT NULL THEN TransactionFee END) AS TransactionFees,
       SUM(CASE WHEN TransactionFee IS NOT NULL THEN Quantity * PriceItem END) AS TransactionValue,
       COUNT(CASE WHEN TransactionFee IS NOT NULL THEN 1 END) as OrdersWithTransactionFees, 
       SUM(CASE WHEN TransactionFee IS NOT NULL THEN Quantity END) as Qty,
       SUM(Quantity * PriceItem) AS WholeMonthTransactionValue         
FROM BuyProductDetails AS a
WHERE MONTH(a.OrderDate) = 3 AND YEAR(a.OrderDate) = 2013
GROUP BY a.SellerID

SQLFiddle上的演示

或者只是在子查询中添加正确的别名

SELECT a.SellerID, 
       SUM(TransactionFee) as TransactionFees,
       SUM(Quantity*a.PriceItem) as TransactionValue,
       COUNT(*) as OrdersWithTransactionFees, 
       SUM(Quantity) as Qty,
       (SELECT SUM(d.Quantity * d.PriceItem)
        FROM BuyProductDetails d
        WHERE d.SellerID = a.SellerID) as WholeMonthTransactionValue 
FROM BuyProductDetails as a
WHERE MONTH(a.OrderDate)=3
AND YEAR(a.OrderDate)=2013
AND TransactionFee IS NOT NULL
GROUP BY a.SellerID

SQLFiddle上的演示

于 2013-03-14T07:43:53.657 回答