我如何根据他们在 SQL 中所属的 table 找到特定人群?

How can I find a certain group of people based on a table which they are part of in SQL?

我在 SQL 中有以下 table:

CREATE TABLE `Trade` (
            Sender BINARY(20) NOT NULL,
            Receiver BINARY(20) NOT NULL,
            Price DECIMAL(36,0) NOT NULL,
            Item VARBINARY(32) NOT NULL,
        ) COLLATE='utf8_general_ci' ENGINE=InnoDB;

基于此 table 我想确定买卖相同商品的交易商,然后根据他们赚取的总利润对他们进行排序。 (总之,我要找profitable经销商)。

我应该按发送方或接收方对交易进行分组,然后尝试对该查询进行进一步查询吗?

通过以下查询,我尝试获取交易者买卖同一商品的所有交易:

SELECT * FROM (SELECT * FROM Trade GROUP BY Receiver) AS r WHERE r.Receiver = Sender;

但是这个查询没有return任何值。

非常感谢任何帮助!

看来你想要这个:

WITH 
cte1 AS ( SELECT sender customer, item, SUM(price) price
          FROM trade
          GROUP BY 1,2 ),
cte2 AS ( SELECT receiver customer, item, SUM(price) price
          FROM trade
          GROUP BY 1,2 )
SELECT customer, item, cte2.price - cte1.price profit
FROM cte1
JOIN cte2 USING (customer, item)

当然有问题。例如,客户可能购买了 3 件商品,但只出售了其中的 2 件......如果 item 是一个名称,而不是唯一标识符,我看不到解决方法。

您可以使用自连接方法:

SELECT
    t1.Sender,
    t1.Receiver,
    t1.Price - t2.Price AS Diff
FROM Trade t1
INNER JOIN Trade t2
    ON t2.Sender = t1.Receiver AND
       t2.Receiver = t1.Sender
ORDER BY
    Diff DESC;

输出取决于您将谁视为相互交易关系中的真正“发送者”。如果你想从另一个方向看,你可以改变排序顺序。