如果在 Postgres 中平局,我如何显示所有结果?
How can I show all the results in case of a draw in Postgres?
所以,我正在使用 PostgreSQL DBMS,并且有以下查询:
Select "CustomerID",Sum("TotalDue") as Total
from "Bike Business"."SalesOrderHeader"
group by "CustomerID"
order by Total desc limit 1;
此查询打印订单成本最高的人的ID和最高成本的数量。但是在平局的情况下,2 个或更多人具有相同的最大订单成本,我希望查询也打印他们的 ID 和最大成本。我怎样才能做到这一点?
基本上,您正在寻找应付总额最高的 1 个或多个客户。
WITH customer_total AS
(
SELECT
CustomerID,
SUM(TotalDue) as Total
FROM
"Bike Business".SalesOrderHeader
GROUP BY
CustomerID
)
SELECT
CustomerID,
Total
FROM
customer_total
WHERE
Total = (SELECT MAX(Total) FROM customer_total);
在这种情况下,确定子查询中的最大到期金额并将其无限制地加入到您的查询中:
Select CustomerID,Sum(TotalDue) as Total
from "Bike Business"."SalesOrderHeader"
join
(Select Sum(TotalDue) as MaxTotal
from "Bike Business"."SalesOrderHeader"
group by CustomerID
order by Total desc
limit 1) t1
group by CustomerID
having Total=t1.MaxTotal
你可以使用子查询
SELECT CustomerID,su FROM (
SELECT CustomerID,sum(val) as su FROM
"Bike Business"."SalesOrderHeader" GROUP By CustomerID) tmp2
WHERE su =(SELECT max(tmp.su) FROM(
SELECT CustomerID,sum(val) as su FROM
"Bike Business"."SalesOrderHeader" GROUP By CustomerID)tmp);
您可以为此使用 window 函数:
select "CustomerID", total
from (
Select "CustomerID",
Sum("TotalDue") as Total,
dense_rank() over (order by Sum("TotalDue") desc) as rnk
from "Bike Business"."SalesOrderHeader"
group by "CustomerID"
) t
where rnk = 1;
这可能比使用子select 或派生的 table.
的等效查询更快
而且它还有一个额外的好处,就是您还可以轻松获得第二或第三高的价值。
所以,我正在使用 PostgreSQL DBMS,并且有以下查询:
Select "CustomerID",Sum("TotalDue") as Total
from "Bike Business"."SalesOrderHeader"
group by "CustomerID"
order by Total desc limit 1;
此查询打印订单成本最高的人的ID和最高成本的数量。但是在平局的情况下,2 个或更多人具有相同的最大订单成本,我希望查询也打印他们的 ID 和最大成本。我怎样才能做到这一点?
基本上,您正在寻找应付总额最高的 1 个或多个客户。
WITH customer_total AS
(
SELECT
CustomerID,
SUM(TotalDue) as Total
FROM
"Bike Business".SalesOrderHeader
GROUP BY
CustomerID
)
SELECT
CustomerID,
Total
FROM
customer_total
WHERE
Total = (SELECT MAX(Total) FROM customer_total);
在这种情况下,确定子查询中的最大到期金额并将其无限制地加入到您的查询中:
Select CustomerID,Sum(TotalDue) as Total
from "Bike Business"."SalesOrderHeader"
join
(Select Sum(TotalDue) as MaxTotal
from "Bike Business"."SalesOrderHeader"
group by CustomerID
order by Total desc
limit 1) t1
group by CustomerID
having Total=t1.MaxTotal
你可以使用子查询
SELECT CustomerID,su FROM (
SELECT CustomerID,sum(val) as su FROM
"Bike Business"."SalesOrderHeader" GROUP By CustomerID) tmp2
WHERE su =(SELECT max(tmp.su) FROM(
SELECT CustomerID,sum(val) as su FROM
"Bike Business"."SalesOrderHeader" GROUP By CustomerID)tmp);
您可以为此使用 window 函数:
select "CustomerID", total
from (
Select "CustomerID",
Sum("TotalDue") as Total,
dense_rank() over (order by Sum("TotalDue") desc) as rnk
from "Bike Business"."SalesOrderHeader"
group by "CustomerID"
) t
where rnk = 1;
这可能比使用子select 或派生的 table.
的等效查询更快而且它还有一个额外的好处,就是您还可以轻松获得第二或第三高的价值。