我遇到一些查询问题。我需要从该查询中获取最大值和product_name:
select
products.product_name,
sum(product_invoice.product_amount) as total_amount
from
product_invoice
inner join
products on product_invoice.product_id = products.product_id
inner join
invoices on product_invoice.invoice_id = invoices.invoice_id
where
month(invoices.invoice_date) = 2
group by
products.product_name
此查询返回如下结果:
product_name | total_amount --------------+-------------- chairs | 70 ladders | 500 tables | 150
如何摆脱这个问题:ladders 500
?
答案 0 :(得分:2)
您可以使用def isCollision(t1, t2):
distance = math.sqrt(math.pow(t1.xcor()-t2.xcor(),2)+math.pow(t1.ycor()-t2.ycor(),2))
if distance < 15:
return True
else:
return False
和order by
:
fetch first 1 row only
并非所有数据库都支持ANSI标准select p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount
fetch first 1 row only;
子句。您可能需要使用fetch first
,limit
或其他一些构造。
请注意,我还引入了表别名 - 它们使查询更容易编写和读取。另外,如果您选择月份,那么您是否也应该选择年份?
在旧版本的SQL Server中,您将使用select top
:
select top 1
要获取最高金额的所有行,请使用select top (1) p.product_name,
sum(pi.product_amount) as total_amount
from product_invoice pi inner join
products p
on pi.product_id = p.product_id inner join
invoices i
on pi.invoice_id = i.invoice_id
where month(i.invoice_date) = 2 -- shouldn't you have the year here too?
group by p.product_name
order by total_amount;
。
答案 1 :(得分:2)
int a;
b=19;
答案 2 :(得分:1)
如果您使用的是SQL Server,那么TOP
可以提供解决方案:
SELECT TOP 1
p.product_name,
SUM(pi.product_amount) AS total_amount
FROM product_invoice pi
INNER JOIN products p
ON pi.product_id = p.product_id
INNER JOIN invoices i
ON pi.invoice_id = i.invoice_id
WHERE
MONTH(i.invoice_date) = 2
GROUP BY
p.product_name
ORDER BY
SUM(pi.product_amount) DESC;
注意:如果可能有多个产品与最高金额相关联,并且您想要所有关联,那么请使用TOP 1 WITH TIES
,例如
SELECT TOP 1 WITH TIES
... (the same query I have above)