繁体   English   中英

过滤 2 列值出现多次的行

[英]Filter rows where 2 column values appear more than once

我有一张像这样的桌子:

SELECT
s.date,
s.orderid,
s.num1,
s.num2,
s.sales,
s.price
FROM sales AS s

导致

date       | orderid | num1 | num 1 | sales | price
2020-11-01 | 1       | a    | aa    | 1     | 10
2020-11-01 | 8       | k    | kk    | 1     | 10
2020-11-02 | 1       | a    | aa    | -1    | 10
2020-11-01 | 2       | b    | bb    | 2     | 8
2020-11-01 | 3       | c    | cc    | 1     | 10
2020-11-01 | 3       | c    | cc    | 2     | 9
2020-11-04 | 18      | u    | uu    | 5     | 2

“orderid”和“num1”应该只出现一次,否则它是一个回报(第二个条目的“销售额”为-1,否定早期的销售额。所以,我需要完全删除这些条目(不保留一行)。否则, “orderid”没有意义,也不需要。

我想按“日期”、“num1”和“num2”分组,总结所有销售额并获得平均价格,同时删除一起出现多次的 orderids+num1。

最终结果应该是:

date       | orderid | num1 | num 1 | sales | price
2020-11-01 | 8       | k    | kk    | 1     | 10
2020-11-01 | 2       | b    | bb    | 2     | 8
2020-11-01 | 3       | c    | cc    | 3     | 9.5
2020-11-04 | 18      | u    | uu    | 5     | 2

如何使用 Groupby 做到这一点? 到目前为止,我有这个:

SELECT
s.date,
s.num1,
s.num2,
SUM(s.sales),
AVG(s.price)
FROM sales AS s
GROUP BY s.date, s.num1, s.num2

您可以使用 window 函数。 根据您的描述(删除多次出现的订单),您可以使用count(*)

select s.date, s.num1, s.num2, SUM(s.sales), AVG(s.price)
from (select s.*, count(*) over (partition by orderid, num1) as cnt
      from sales s
     ) s
where cnt = 1
group by s.date, s.num1, s.num2;

我怀疑你真的想要row_number() ,所以你保留重复的行之一。

您可以使用group byhaving以下内容:

SELECT max(s.date) as date,
       S.orderid,
       s.num1,
       s.num2,
       SUM(s.sales),
       AVG(s.price)
  FROM sales AS s
GROUP BY s.orderid, s.num1, s.num2
Having sum(sales) > 0;

问题:

这是一个事务日志,其中您的 orderId 1 和销售条目 10、5、-1、7、8 应该导致值 15? 10 和 5 被 -1 否定。 如果是这样,您需要执行以下查询:a) 查找该 orderId 的最后一个 -1 之后的所有行,并对销售值求和。

这种情况是相同 orderId 5、6、-1、7、9、-1、10、2 的销售值,最终金额应仅使用 10 和 2

就像是

查询 1 - 查找每个订单 id 的最大(日期)值,其中销售额为 -1 查询 2 - 使用查询 1 获取每个 orderId 的所有交易,其中日期 > 查询 1 中的日期

WITH(在此处定义查询 1)
SELECT s.OrderId,Sum(s.sales) 作为 TotalSales,Avg(s.Price) 作为 AveragePrice
FROM 销售
左外连接(查询 1) q1 ON q1.OrderId
WHERE(q1.Date 为空)或(s.Date > q1.Date)
GROUP BY s.OrderId

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM