我有一张看起来像
的桌子客户:
| CUSTOMER_ID | CUSTOMER_NAME | BANK_ID |
-----------------------------------------
| 1 | a | b |
| 2 | b1 | c |
| 3 | b1 | d |
| 4 | C | e |
| 5 | a | f |
| 6 | b1 | g |
我有一个查询,查找不唯一的所有客户名称并将它们组合在一起。它还为每个组中的行分配行号。 此查询的输出为:
RowNumber|customer_id | customer_name |
1 | 1 | a |
2 | 5 | a |
1 | 2 | b1 |
2 | 3 | b1 |
3 | 6 | b1 |
我想迭代所有组。对于每个组,我想加入组成员,并在不同的表中使用行。是否有任何方法可以对每个子组进行操作并对每个子组中的项应用业务逻辑?
例如:假设对于每个组,如果该组中的所有客户都住在同一个地方并且在同一个地方工作,我希望离开第一个客户。
我有下表:
|客户ID |地址|职场名称|
| 1 | street1 | WORK1 |
| 2 | street2 | WORK1 |
| 3 | street1 | WORK2 |
| 4 | street5 | work7 |
| 5 | street1 | WORK1 |
| 6 | street2 | WORK1 |
您可以注意到,只有第一组中的客户在同一个地方居住和工作(客户ID:1,5)。如果你看第二组(客户编号:2,3,6) - 他们并不都在同一个地方生活和工作。 此查询的结果将是:客户ID 5,因为它位于客户ID为5的同一组中,并且它们在同一个地方生活和工作。但客户5是该组中的第二位。
最简单的方法是什么?
答案 0 :(得分:0)
试试这个:
WITH A(Customer_id, Customer_name)
AS(SELECT Customer_id, Customer_name
FROM Customer
WHERE Customer_name IN
(SELECT Customer_name FROM Customer
GROUP BY Customer_name
HAVING COUNT(Customer_name) >1)
)
SELECT RANK() OVER (ORDER BY Customer_id ASC) AS RowNumber
, Customer_id, Customer_Name
FROM A
ORDER BY Customer_name, Customer_id;
或者您也可以使用JOIN
WITH A(Customer_id, Customer_name)
AS (SELECT c.Customer_id, c.Customer_name
FROM Customer c
JOIN
(SELECT Customer_id FROM Customer
WHERE Customer_name IN ( SELECT Customer_name FROM Customer
GROUP BY Customer_name
HAVING COUNT(Customer_name) >1)
) AS c1
ON c.Customer_id = C1.customer_id)
SELECT RANK() OVER (ORDER BY A.customer_id ASC) AS RowNumber
, Customer_id, Customer_Name
FROM A
ORDER BY Customer_name, Customer_id;
答案 1 :(得分:0)
我在单个查询中找不到任何方法。我创建了一个执行我想做的游标:迭代一个表的所有行,应用业务逻辑并将相关行插入到输出表中。