我需要帮助,我可以创建一个qquery,找出哪个服装类别售价超过50美元 到目前为止我写过这个:
SELECT
ITEM_TYPE.Description AS [Item Type Name],
ITEM.ItemID * price AS [Total Spent]
FROM ITEM
INNER JOIN ITEM_TYPE ON ITEM.ItemTypeID = ITEM_TYPE.ItemTypeID
INNER JOIN ORDER_ITEM ON ITEM.ItemID = ORDER_ITEM.ItemID
where ITEM_TYPE.Description Like '%Ladies%'
但输出应仅显示1行“服装女士”,总销售额为80.50
答案 0 :(得分:0)
我想你想要一个GROUP BY
子句和聚合函数SUM()
:
SELECT
ITEM_TYPE.Description AS [Item Type Name],
SUM(price) AS [Total Spent] -- ### apply SUM()
FROM ITEM
INNER JOIN ITEM_TYPE ON ITEM.ItemTypeID = ITEM_TYPE.ItemTypeID
INNER JOIN ORDER_ITEM ON ITEM.ItemID = ORDER_ITEM.ItemID
where ITEM_TYPE.Description Like '%Ladies%'
GROUP BY ITEM_TYPE.Description -- ### add grouping for SUM()
我怀疑你想通过Item的ID多次price
。如果price
是订单项的总价格,则只需SUM(price)
,如上所述。如果price
是商品价格,您可能需要SUM(price * quantity)
之类的商品。
如果您需要将总数舍入为2位小数,请使用ROUND
:
ROUND(SUM(ITEM.ItemID * price), 2) AS [Total Spent] -- ### apply ROUND()
答案 1 :(得分:0)
你会做一个SUM,这是一个聚合。应用聚合时,必须按任何非聚合列进行分组。要过滤聚合,可以使用HAVING为SELECT指定条件。例如:
SELECT
ITEM_TYPE.Description AS [Item Type Name],
SUM(ITEM.ItemID * price) AS [Total Spent] --aggregate column
FROM ITEM
INNER JOIN ITEM_TYPE ON ITEM.ItemTypeID = ITEM_TYPE.ItemTypeID
INNER JOIN ORDER_ITEM ON ITEM.ItemID = ORDER_ITEM.ItemID
where ITEM_TYPE.Description Like '%Ladies%'
GROUP BY ITEM_TYPE.Description --GROUP BY the non aggregate columns
HAVING SUM(ITEM.ItemID * price) > 50 --HAVING filters the aggregate column
答案 2 :(得分:0)
您必须使用GROUP BY
和HAVING
子句。 GROUP BY
用于组合所有具有相同描述的行,HAVING
用于过滤价格总和超过50的行。
SELECT
ITEM_TYPE.Description AS [Item Type Name],
SUM(ITEM.ItemID * price) AS [Total Spent]
FROM ITEM
INNER JOIN ITEM_TYPE ON ITEM.ItemTypeID = ITEM_TYPE.ItemTypeID
INNER JOIN ORDER_ITEM ON ITEM.ItemID = ORDER_ITEM.ItemID
WHERE ITEM_TYPE.Description Like '%Ladies%'
GROUP BY ITEM_TYPE.Description
HAVING SUM(ITEM.ItemID * price) > 50
为了更好地理解拥有和分组条款,您需要仔细阅读有关它们https://www.w3schools.com/sql/sql_having.asp
的更多信息