Divide by Subquery returning 'Subquery returned more than 1 value.' error

有些话、适合烂在心里 提交于 2021-01-29 17:20:18

问题


I have the following table in which I have two sales orders and each sales order has a different number of transactions.

SaleOrder Transaction Amount
S1 T1 20
S1 T2 20
S2 T1 15
S2 T2 15
S2 T3 15

The problem is I am getting the total sales order amount against each transaction in SQL Server table when in fact they need to be divided equally among the number of transactions like this:

SaleOrder Transaction Amount
S1 T1 10
S1 T2 10
S2 T1 5
S2 T2 5
S2 T3 5

I've written the following query:

SELECT SalesOrder,
     Transaction,
     Max(Amount) / (SELECT COUNT(Transaction) AS Transaction FROM Test_Table GROUP BY SalesOrder)
    FROM Test_Table
    GROUP BY SalesOrder,
        Transaction

But it is giving me 'Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <=, >, >= or when the subquery is used as an expression.' error. Can someone explain what this is and how to rectify this error?


回答1:


I don't think you want group by, just window functions:

SELECT SalesOrder, Transaction,
       Amount) / COUNT(*) OVER (PARTITION BY salesorder)
FROM Test_Table;



回答2:


Since in the subquery you GROUP BY SalesOrder it returns 1 row for each SalesOrder.
But you want the number of transactions for the specific SalesOrder.
Use MAX() and COUNT() window functions:

SELECT DISTINCT SalesOrder, Transaction, 
       MAX(Amount) OVER (PARTITION BY SalesOrder, Transaction) / 
       COUNT(*) OVER (PARTITION BY SalesOrder)
FROM Test_Table

If the data type of the column Amount is INTEGER then SQL Server will perform integer division, so maybe you need to multiply first by 1.0 so that you get a correct result with decimal places:

SELECT DISTINCT SalesOrder, Transaction, 
       1.0 * MAX(Amount) OVER (PARTITION BY SalesOrder, Transaction) / 
       COUNT(*) OVER (PARTITION BY SalesOrder)
FROM Test_Table 



回答3:


Try this one

SELECT SaleOrder, [Transaction]
    , Max(Amount) / COUNT([Transaction]) over (partition by SaleOrder)
FROM Test_Table GROUP BY SaleOrder,[Transaction]


来源:https://stackoverflow.com/questions/65441405/divide-by-subquery-returning-subquery-returned-more-than-1-value-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!