根据规则创建数据透视表

时间:2017-12-06 19:37:45

标签: sql sql-server tsql

我有一个像:

这样的数据集
+---------------+----+
| Grade         | ID |
+---------------+----+
| Copper        | 1  |
+---------------+----+
| Copper        | 2  |
+---------------+----+
| Copper Bonded | 2  |
+---------------+----+
| Fiber         | 3  |
+---------------+----+
| Fiber         | 4  |
+---------------+----+

我想得到这样的结果:

+----+--------+
| ID | Copper |
+----+--------+
| 1  | A      |
+----+--------+
| 2  | B      |
+----+--------+
| 3  | C      |
+----+--------+
| 4  | C      |
+----+--------+

规则集是这样的:

A :  Copper only
B :  Copper and Copper Bonded
C :  Fiber only

这是一个支点,我如何将其表达为SQL查询?

3 个答案:

答案 0 :(得分:2)

好的,你肯定需要使用CASE,它很复杂,你只给了我们一个像这样的东西"规则集,所以我会给你一些psuedocode指向你的方向解决方案,你的最终代码将是"类似这样的"取决于您的实际规则:

SELECT DISTINCT ID, 
  CASE 
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND EXISTS(SELECT a row with this ID WHERE Grade='Copper Bonded')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper' or 'Copper Bonded')
        THEN 'B'
    WHEN EXISTS(SELECT a row with this ID WHERE Grade='Copper')
      AND NOT EXISTS(SELECT a row with this ID WHERE Grade is something other than 'Copper')
        THEN 'A'
    WHEN ... {by now you should be starting to get the idea}
  END AS Copper
FROM MyTable t1  --be sure to alias your table so you can correlate your EXISTS subqueries

答案 1 :(得分:2)

我使用了分隔技巧并评估了:

create table #temp  (grade varchar(100),id int)
insert into #temp
values
('Copper',1)
,('Copper',2)
,('Copper bonded',2)
,('Fiber',3)
,('Fiber',4)

;with cte as
(
select distinct id,stuff((select '|' + grade
                from #temp
                where id = t1.id
                group by grade
                order by grade
                for xml path('')
                ),1,1,'') as Combined
from #temp t1
)

select id,
    case combined
        when 'Copper' then 'A'
        when 'Copper|Copper Bonded' then 'B'
        when 'Fiber' then 'C'
        else 'Unknown'
    end as Copper 
from cte



drop table #temp

结果:

id  Copper
1   A
2   B
3   C
4   C

答案 2 :(得分:1)

它真的很奇怪的情况和条件,但这是一个想法:

sku

结果:

CREATE TABLE T (
    ID INT IDENTITY (1,1),
    GRADE VARCHAR(25)
    );
INSERT INTO T VALUES
('Copper'),
('Copper'),
('Copper Bonded'),
('Fiber'),
('Fiber');
with cte as (
SELECT ID, GRADE, row_number () over (partition by grade order by id) rn
FROM T
),
Final as (
select id, case when grade = 'Copper'and rn = 1 then 'A' 
                when grade= 'Copper Bonded' then 'B'
                when grade = 'Fiber' then 'C' end k
from cte)

select  row_number () over (order by k) id,k as Copper 
from final
where k is not null