SQL:UN-PIVOT并按个人分数分开

时间:2017-03-08 18:51:26

标签: sql sql-server sql-server-2008 unpivot

我正在使用SQL Server 2008,我正在尝试编写一个将列拆分为单独行的查询。我正在提取计数数据,需要将其转换为单独的分数。

示例:
5名学生回答“总是”,回答“总是”= 3分; 4名学生回答'通常'并回答'通常'= 2分

我希望有一个名为'Score'的字段,其中包含5行3行和4行,而不是名为'always'且计数为5的字段和名为'always'且字数为4的字段。 2。

我已经使用UNPIVOT启动了我的查询,但是,它没有像所描述的那样拆分数据。我在下面列出了样本数据和我想要的结果。任何帮助,将不胜感激。

Always = 3 points  
Usually = 2 points      
Sometimes = 1 points    
Never = 0 points 

示例数据:

CREATE TABLE #TEST(QUESTION VARCHAR(15), STUDENT VARCHAR(15), STARTDATE DATE, ALWAYS INT, USUALLY INT, SOMETIMES INT, NEVER INT)

INSERT #TEST(QUESTION, STUDENT, STARTDATE, ALWAYS, USUALLY, SOMETIMES, NEVER)
VALUES
('A','BOB','01/01/2016',2,1,1,2),
('A','BOB','03/01/2016',3,1,1,0),
('A','JIM','01/01/2016',2,1,2,0),
('A','JIM','03/01/2016',4,1,0,0),
('BB','BOB','03/01/2016',2,1,1,2),
('BB','BOB','07/01/2016',3,1,1,0),
('BB','JIM','03/01/2016',2,1,2,0),
('BB','JIM','07/01/2016',4,1,0,0)  

查询:

WITH A AS (
    SELECT *
    FROM #TEST
    --WHERE 
    --  QUESTION = 'A' 
    --AND STUDENT IN ('BOB','JIM')
    --AND STARTDATE = '2016-01-01'
)   
SELECT QUESTION, STUDENT, STARTDATE, SCORE
FROM 
    (   SELECT QUESTION, STUDENT, STARTDATE, ALWAYS, USUALLY, SOMETIMES, NEVER
        FROM A
    ) P
UNPIVOT
    ( SCORE FOR Z IN (ALWAYS, USUALLY, SOMETIMES, NEVER)
    ) AS unpvt  

预期结果:前2行

QUESTION|STUDENT|STARTDATE|SCORE|
--------+-------+---------+-----+
A       |BOB    |1/1/2016 |3    |--ALWAYS
A       |BOB    |1/1/2016 |3    |--ALWAYS
A       |BOB    |1/1/2016 |2    |--USUALLY
A       |BOB    |1/1/2016 |1    |--SOMETIMES
A       |BOB    |1/1/2016 |0    |--NEVER
A       |BOB    |1/1/2016 |0    |--NEVER
A       |BOB    |3/1/2016 |3    |--ALWAYS
A       |BOB    |3/1/2016 |3    |--ALWAYS
A       |BOB    |3/1/2016 |3    |--ALWAYS
A       |BOB    |3/1/2016 |2    |--USUALLY
A       |BOB    |3/1/2016 |1    |--SOMETIMES

3 个答案:

答案 0 :(得分:1)

借助CROSS APPLY和ad-hoc计数表

Select A.Question
      ,A.Student
      ,A.StartDate
      ,B.Score
 From  #Test A
 Cross Apply ( values (Always,3)
                     ,(Usually,2)
                     ,(Sometimes,1)
                     ,(Never,0) 
              ) B(Cnt,Score)
 Join (Select Top 100 N=Row_Number() Over (Order By Number) From master..spt_values ) C
   on (C.N <= B.Cnt)
 Where Student='Bob' and question ='A'

返回

Question    Student StartDate   Score
A           BOB     2016-01-01  3
A           BOB     2016-01-01  3
A           BOB     2016-01-01  2
A           BOB     2016-01-01  1
A           BOB     2016-01-01  0
A           BOB     2016-01-01  0
A           BOB     2016-03-01  3
A           BOB     2016-03-01  3
A           BOB     2016-03-01  3
A           BOB     2016-03-01  2
A           BOB     2016-03-01  1

答案 1 :(得分:0)

如果您有可管理的列数要进行展开,我通常会为每个列进行单独查询,并与import {TestBed, ComponentFixture} from '@angular/core/testing'; import { NgModel } from '@angular/forms'; import {Component, DebugElement } from '@angular/core'; import {By} from "@angular/platform-browser"; import {MinValueDirective} from './min-value.directive'; @Component({ template: `<input type="number" dleGbMinValue="0">` }) class TestMinValueDirectiveComponent { } describe('Directive: MinValueDirective', () => { let component : TestMinValueDirectiveComponent; let fixture: ComponentFixture<TestMinValueDirectiveComponent>; let inputEl: DebugElement; beforeEach(() => { TestBed.configureTestingModule({ declarations: [TestMinValueDirectiveComponent, MinValueDirective] }); fixture = TestBed.createComponent(TestMinValueDirectiveComponent); component = fixture.componentInstance; inputEl = fixture.debugElement.query(By.css('input')); fixture.detectChanges(); }); it('should stop at min value on change', () => { expect(inputEl.nativeElement.value).toEqual(''); inputEl.nativeElement.value='-5'; inputEl.triggerEventHandler('change', null); fixture.detectChanges(); expect(inputEl.nativeElement.value).toEqual(0); }); }); 结合使用。

以下是一般概念:

UNION ALL

答案 2 :(得分:0)

使用with a as ( select * from #test where question = 'A' and student = 'bob' --and student in ('bob','jim') --and startdate = '20160101' ) , points as ( select Answer, Points from (values ('Always',3),('Usually',2),('Sometimes',1),('Never',0) ) p (Answer,Points) ) , numbers as ( select n from (values(1),(2),(3),(4),(5),(6),(7),(8),(9) ) t(n) ) , unp as ( select a.question , a.student , StartDate=convert(varchar(10),a.startdate,120) , x.AnswerCount , x.Answer from a cross apply ( values ([Always],'Always') , ([Usually],'Usually') , ([Sometimes],'Sometimes') , ([Never],'Never') ) x (AnswerCount,Answer) ) select unp.question , unp.student , unp.startdate , score = p.points , unp.answer from unp inner join numbers n on n.n<=unp.AnswerCount inner join points p on unp.answer=p.answer 取消您的数据,1-9的数字表和积分表,我们可以这样做:

+----------+---------+------------+-------+-----------+
| question | student | startdate  | score |  answer   |
+----------+---------+------------+-------+-----------+
| A        | bob     | 2016-01-01 |     3 | Always    |
| A        | bob     | 2016-01-01 |     3 | Always    |
| A        | bob     | 2016-01-01 |     2 | Usually   |
| A        | bob     | 2016-01-01 |     1 | Sometimes |
| A        | bob     | 2016-01-01 |     0 | Never     |
| A        | bob     | 2016-01-01 |     0 | Never     |
| A        | bob     | 2016-01-03 |     3 | Always    |
| A        | bob     | 2016-01-03 |     3 | Always    |
| A        | bob     | 2016-01-03 |     3 | Always    |
| A        | bob     | 2016-01-03 |     2 | Usually   |
| A        | bob     | 2016-01-03 |     1 | Sometimes |
+----------+---------+------------+-------+-----------+

rextester演示:reference

返回:

:app:transformClassesWithDexForDebug FAILED

FAILURE: Build failed with an exception.

*What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: java.lang.RuntimeException:java.lang.RuntimeException:com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: java.lang.UnsupportedOperationException

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 14.034 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have set up your Android development environment:
https://facebook.github.io/react-native/docs/android-setup.html