优先客户群

时间:2016-03-02 10:44:29

标签: sql-server

我的客户拥有来自不同产品组的产品。例如:

Client  Product group
1       All-in-one
1       Senior
2       All-in-one
2       Other
3       Senior
3       Other
4       Other

产品组具有优先级,因此,如果您拥有一体化和高级产品组的产品,则您将被归类为一体化客户。

优先考虑的产品组是:

  1. 所有功能于一身的
  2. 高级
  3. 其他
  4. 我想要一个每个客户只出现一次的视图:

    Client  Product group
    1       All-in-one
    2       All-in-one
    3       Senior
    4       Other
    

    这可以在没有大量观点的情况下一步完成吗?

2 个答案:

答案 0 :(得分:1)

如果仅保留那些产品组,则第一个可用,第二个可以灵活订购但使用ctes

select id,min(pg) from #client
group by id

;with cte
as
(
select 
id,
min(case when pg='All-in-one'  then 1
 when pg='senior' then 2
 when pg='other' then 3
 end ) pg
 from 
 #client
 group by id
 )
 select id,
 case pg when 1 then 'All-in-one'
  when 2 then 'Senior'
  when 3 then 'other'
 end as 'PG'
 from cte

答案 1 :(得分:0)

试试这个(你不需要使用clients_groups cte,因为你已经有了这个表):

;WITH clients_groups AS (
SELECT *
FROM (VALUES
(1, 'All-in-one'),
(1, 'Senior'),
(2, 'All-in-one'),
(2, 'Other'),
(3, 'Senior'),
(3, 'Other'),
(4, 'Other')) as cg (Client, Product_group)
),
final AS (
SELECT ROW_NUMBER() OVER(PARTITION BY Client ORDER BY id Asc) AS R,g.Client, p.Name 
FROM clients_groups g
LEFT JOIN (VALUES
(1, 'All-in-one'),
(2, 'Senior'),
(3, 'Other')) as p(id, name) ON g.Product_group = p.name)

SELECT Client,Name
FROM final 
WHERE R = 1

结果:

Client      Name
----------- ----------
1           All-in-one
2           All-in-one
3           Senior
4           Other

(4 row(s) affected)