我需要一个清单,该清单在给定年份内购买的产品总额超过给定年份最大金额的80%。我有一个清单,列出所有人员及其每年的总金额,但我不知道该如何过滤。我尝试使用MAX函数并使用最高的SUM,但它不起作用或我做错了。 我当前的查询是:
<template>
<div>
<div class="wrapper">
<b-table
:data="users">
<template slot-scope="props">
<b-table-column label="id" sortable>
{{props.row.id}}
</b-table-column>
<b-table-column field="content" label="content" sortable>
{{props.content}}
</b-table-column>
<b-table-column field="color" label="color" sortable>
{{props.color}}
</b-table-column>
</template>
</b-table>
</div>
</div>
</template>
答案 0 :(得分:1)
您可以使用子查询进行过滤
SELECT * FROM (SELECT (p.LastName + ' ' + p.FirstName) AS 'Customer',
s.CustomerID AS 'CustomerId', YEAR(s.OrderDate) AS Rok,
SUM(s.SubTotal) AS 'Amount', COUNT(*) AS 'number of purchases'
FROM Sales.SalesOrderHeader s JOIN Sales.Customer c
ON s.CustomerID = c.CustomerID
JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
GROUP BY s.CustomerID, YEAR(s.OrderDate), p.LastName, p.FirstName
ORDER BY s.CustomerID, YEAR(s.OrderDate)) z
WHERE z.Amount>80;
您需要实现的逻辑可以写在where子句中,这是我使用的示例过滤器
答案 1 :(得分:1)
如果我正确理解了您的问题,那应该没问题:
with cte as (
SELECT
(p.LastName + ' ' + p.FirstName) AS 'Customer', s.CustomerID AS 'CustomerId', YEAR(s.OrderDate) AS Rok, SUM(s.SubTotal) AS 'Amount', COUNT(*) AS 'number of purchases'
FROM Sales.SalesOrderHeader s JOIN Sales.Customer c ON s.CustomerID = c.CustomerID
JOIN Person.Person p ON c.PersonID = p.BusinessEntityID
GROUP BY s.CustomerID, YEAR(s.OrderDate), p.LastName, p.FirstName
), Max80Percent as
(
select
*
,0.8 * MAX(Amount) OVER (PARTITION BY Rok) as Threshold
from cte
)
select
*
from Max80Percent
where Amount > Threshold