我有一个表,代表一组集合,这些集合由该组中称为序列的列排序:
| GroupId | Collection | Sequence |
|---------|------------|----------|
| 002 | A.2018 | 1 |
| 002 | A.2017 | 2 |
| 003 | P.2018 | 1 |
| 003 | L.2018 | 2 |
| 003 | R.2018 | 3 |
| 003 | M.2018 | 4 |
在另一个表格中,我按收集和细分列出了客户销售额:
| Collection | Segment | Customer | Sales |
|------------|---------|----------|--------|
| A.2018 | 002 | C001030 | 304.30 |
| A.2017 | 002 | C001030 | 493.10 |
| L.2018 | 002 | C001030 | 232.33 |
| L.2018 | 010 | C001030 | 343.12 |
| R.2018 | 002 | C001030 | 434.23 |
| M.2018 | 002 | C001030 | 121.12 |
我想通过GroupID获取客户在该细分市场中销售的第一个集合(按集合顺序排序)。
| GroupID | Collection | Segment | Customer | Sales |
|---------|------------|---------|----------|--------|
| 002 | A.2018 | 002 | C001030 | 304.30 |
| 003 | L.2018 | 002 | C001030 | 232.33 |
| 003 | L.2018 | 010 | C001030 | 343.12 |
答案 0 :(得分:1)
SELECT * FROM (
with t1 as (
SELECT '002' as groupid, 'A.2018' as collection, 1 as sequence FROM DUAL UNION ALL
SELECT '002','A.2017',2 FROM DUAL UNION ALL
SELECT '003','P.2018',1 FROM DUAL UNION ALL
SELECT '003','L.2018',2 FROM DUAL UNION ALL
SELECT '003','R.2018',3 FROM DUAL UNION ALL
SELECT '003','M.2018',4 FROM DUAL
),
t2 as (
SELECT 'A.2018' as collection,'002' as segment ,'C001030' as customer,304.30 as sales FROM DUAL UNION ALL
SELECT 'A.2017','002','C001030',493.10 FROM DUAL UNION ALL
SELECT 'L.2018','002','C001030',232.33 FROM DUAL UNION ALL
SELECT 'L.2018','010','C001030',343.12 FROM DUAL UNION ALL
SELECT 'R.2018','002','C001030',434.23 FROM DUAL UNION ALL
SELECT 'M.2018','002','C001030',121.12 FROM DUAL
)
SELECT groupid,
t1.collection,
segment,
customer,
sales,
row_number() over (partition by groupid,segment,customer order by t1.collection ASC) rn
FROM t2,
t1
WHERE t1.collection = t2.collection
)
WHERE rn = 1
输出:
GROUPID COLLECTION SEGMENT CUSTOMER SALES RN
002 A.2017 002 C001030 493.1 1
003 L.2018 002 C001030 232.33 1
003 L.2018 010 C001030 343.12 1
但是:
您期望的002组的输出是
002 | A.2018 | 002 | C001030 | 304.30 |
您写道:
“第一个集合(按集合顺序排序)”
所以我认为这里的第一个集合是A.2017
。
答案 1 :(得分:0)
种类
select GroupId, Collection, Segment, Customer, Sales
from(
select t1.GroupId, t1.Collection, t2.Segment, t2.Customer, t2.Sales,
row_number() over(partition by t2.Segment, t2.Customer order by t1.Sequence) rn
from t1
join t2 on t1.Collection = t2.Collection
) t
where rn=1
答案 2 :(得分:0)
如果我理解正确,则可以使用窗口功能:
select cs.*
from (select c.*, s.segment, s.customer, s.sales,
row_number() over (partition by c.collection, s.segment, s.customer order by c.sequence) as seqnum
from collections c join
sales s
on c.collection = s.collection
) cs
where seqnum = 1;