销售摘要的SQL查询

时间:2010-06-30 13:47:11

标签: tsql

请帮我解决这个问题

select pName,Price, (Price*Quantity) as SalesValues from saleslog where 
BillDate='12-10-2010' and pGroup=15 group by pname, Quantity, Price;

此查询旨在根据日期显示销售摘要,但它显示的是重复的产品名称。

以上查询的输出

MAK 2 T OIL 5LTR.   635    3175
MAK 2 T OIL 5LTR.   635    6350
MAK ELITE 3LTR     422    6330
MAK ELITE 3LTR     422    8440
SYSTEM PURGE         305    6100
SYSTEM PURGE         305    15250

您可以看到重复的产品名称,但我想根据产品名称进行销售总结。

感谢...................

3 个答案:

答案 0 :(得分:4)

SELECT pName, SUM(Price * Quantity) AS SalesValues
FROM   saleslog
WHERE  BillDate = '12-10-2010' 
       AND pGroup = 15
GROUP BY
       pname

我删除了Price,因为它可能(可能)发生变化,并且不清楚要输出哪一个。

如果价格没有变化,请使用:

SELECT pName, MIN(price), SUM(Price * Quantity) AS SalesValues
FROM   saleslog
WHERE  BillDate = '12-10-2010' 
       AND pGroup = 15
GROUP BY
       pname

答案 1 :(得分:2)

试试这个:

select pName, price, SUM(Price*Quantity) as SalesValues 
from saleslog 
where BillDate='12-10-2010' and pGroup=15 
group by pname, price

您只需按select子句中不在聚合中的列进行分组。我假设每种产品都有相同的价格。

如果你使用聚合显示它(例如MIN或MAX),你甚至不必按价格分组:

select pName, MAX(price), SUM(Price*Quantity) as SalesValues 
from saleslog 
where BillDate='12-10-2010' and pGroup=15 
group by pname

以下是GROUP BY子句的一些文档:

  

通过一个或多个列或表达式的值将选定的行集合分组为一组摘要行。每组返回一行。 SELECT子句列表中的聚合函数提供有关每个组而不是单个行的信息。

答案 2 :(得分:1)

这是您的原始查询:

select pName,Price, (Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname, Quantity, Price;

现在你说你希望它只按pName分组。让我们这样做。

select pName,Price, (Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

现在,当然,它会出错。所以我们需要在其他列上加上一些聚合。 SUM SalesValues列是有意义的。

select pName,Price, SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

价格栏仍然是一个问题。什么聚合器对此有意义?这取决于。我猜你可以做MAX,MIN或AVERAGE。但实际上它需要被遗漏,或者被添加回分组。如果它被添加回组中,则每个pName不再有一行。如果您确实在Prince上放置了聚合器,请务必更改列的名称以反映其含义。

/* Leave out the Price completely. (My favorite option.) */
select pName,SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

/* Group by Price. You now have multiple rows per pName. */
select pName,Price, SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname, Price;

/* Average the Price. (OK, but could lead to confusion.) */
select pName,AVG(Price) as AveragePrice, SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

/* Max Price. (Almost useless). */
select pName,MAX(Price) as MaximumPrice, SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

/* Min Price. (Almost useless). */
select pName,MIN(Price) as MinimumPrice, SUM(Price*Quantity) as SalesValues from saleslog where  
BillDate='12-10-2010' and pGroup=15 group by pname;

我不建议汇总价格,(尤其是MAX和MIN),因为当人们试图使用该值时,它可能会导致混乱。