SQL - Select 行基于列值和
SQL - Select rows based on column value and
我有一个 table 这样的:
CustomerID - ProductID - Score
Customer1 - Product1 -- 9
Customer1 - Product2 -- 10
Customer2 - Product3 -- 11
Customer2 - Product4 -- 7
Customer3 - Product1 -- 6
我想按 customerID 分组。并只为得分最高的客户选择那一行
所以,我的 table 应该变成:
Customer1 - Product2 -- 10
Customer2 - Product3 -- 11
Customer3 - Product1 -- 6
如何在 SQL 中执行此操作?
尝试 SQL rank
函数对子组中的行和 select 第一行进行排序,如下所示。
Select * from
(
Select CustomerId,
productId,
Score,
Rank() Over (PARTITION BY CustomerId ORDER BY Score DESC) AS Rnk
) query Where rnk = 1
试试这个:
SELECT CUST_ID,PROD_ID, MAX(SCORE) AS SCORE FROM TABLE GROUP BY CUST_ID,PROD_ID;
您需要将 'group by' 转换为包含最大值的临时 table,然后内部连接到您的临时 table。
https://www.w3schools.com/sql/sql_groupby.asp
http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
你不能在单个 select 语句中做你想做的事情,因为 SQL 服务器直到第一个 select 语句已完成 运行。这就是为什么您需要编写第二个查询并根据与 temp table
具有相同值的行进行连接
我有一个 table 这样的:
CustomerID - ProductID - Score
Customer1 - Product1 -- 9
Customer1 - Product2 -- 10
Customer2 - Product3 -- 11
Customer2 - Product4 -- 7
Customer3 - Product1 -- 6
我想按 customerID 分组。并只为得分最高的客户选择那一行 所以,我的 table 应该变成:
Customer1 - Product2 -- 10
Customer2 - Product3 -- 11
Customer3 - Product1 -- 6
如何在 SQL 中执行此操作?
尝试 SQL rank
函数对子组中的行和 select 第一行进行排序,如下所示。
Select * from
(
Select CustomerId,
productId,
Score,
Rank() Over (PARTITION BY CustomerId ORDER BY Score DESC) AS Rnk
) query Where rnk = 1
试试这个: SELECT CUST_ID,PROD_ID, MAX(SCORE) AS SCORE FROM TABLE GROUP BY CUST_ID,PROD_ID;
您需要将 'group by' 转换为包含最大值的临时 table,然后内部连接到您的临时 table。
https://www.w3schools.com/sql/sql_groupby.asp
http://codingsight.com/introduction-to-temporary-tables-in-sql-server/
你不能在单个 select 语句中做你想做的事情,因为 SQL 服务器直到第一个 select 语句已完成 运行。这就是为什么您需要编写第二个查询并根据与 temp table
具有相同值的行进行连接