具有条件的两个表的SQL Server总和列

问题描述 投票:1回答:4

我有两张桌子:

销售:

 SaleID | DayNumber | Quantity | ProductID
    1   | 1         | 10       | 1
    2   | 1         | 150      | 4
    3   | 1         | 70       | 6
    4   | 2         | 30       | 2
    5   | 2         | 40       | 3
    6   | 2         | 45       | 5
    7   | 2         | 15       | 8

和产品:

ProductID | Price
1         | 12
2         | 52
3         | 643
4         | 42
5         | 75
6         | 53
7         | 2
8         | 7

所以我想得到一些结果,但我不知道我该怎么做。我想计算第2,3和4天销售产品的总和,以及每天的平均收入。

sql sql-server
4个回答
0
投票

我认为你需要加入查询这个简单的总和

create table #sales
(id int not null identity(1,1),
 DayNUmber int,
 Quantity int,
 ProductID int)

 create table #Products(
 id int not null identity(1,1),
 Price money
 )
insert #sales
values
(1,10,1),
(1,150,4),
(1,70,6),
(2,30,2),
(2,40,3),
(2,45,5),
(2,5,8);

insert #Products
values
(12),
(52),
(643),
(42),
(75),
(53),
(2),
(5);



select 
sum(s.Quantity*p.Price) as [sum],
s.DayNumber from #sales s inner join #Products p
on s.ProductID=p.id  where s.DayNumber in (2,3)
group by s.DayNUmber

0
投票

加入公共ID。取数量*价格的总和。按日分组并根据需要进行过滤。

SELECT
SUM(Quantity*Price)
,DayNumber
FROM Sales s
INNER JOIN PRODUCT p ON p.ProductID = s.ProductID
WHERE DayNumber IN(2,3,4)
GROUP BY DayNumber

0
投票

要完成这项工作,您需要JOIN查询中的两个表。然后,您可以使用SUM计算已售产品和收入的总和。要过滤第2,3和4天,您可以在IN子句中使用WHERE

SELECT S.DayNumber, SUM(S.Quantity) AS 'Products Sold', SUM(S.Quantity * P.Price) AS 'Total Earnings'
FROM Sales AS S JOIN Products AS P ON S.ProductID = P.ProductID
WHERE S.DayNumber IN (2, 3, 4)
GROUP BY S.DayNumber

0
投票

您需要每天AVG和每日总销售额。根据需要过滤

SELECT SUM(p.Price * s.Quantity) TotalsalePerday, AVG(p.Price * s.Quantity) AvgsalePerday ,s.DayNumber from SO_Products p
    INNER JOIN SO_Sales s ON p.ProductID = s.ProductID
    GROUP BY DayNumber
    ORDER BY DayNumber

/ ------------------------ OUTPUT ------------------------ /

TotalsalePerday AvgsalePerday DayNumber
--------------- ------------- -----------
10130           3376          1
30760           7690          2

(2 row(s) affected)
© www.soinside.com 2019 - 2024. All rights reserved.