我有这张桌子:
ID | Status | Date
----+----------+--------------
1 | 1 | 01-01-2017
2 | 1 | 26-04-2016
2 | 4 | 20-10-2016
3 | 1 | 05-11-2015
3 | 2 | 20-03-2016
4 | 4 | 06-06-2015
5 | 1 | 10-04-2017
5 | 3 | 21-12-2016
5 | 2 | 25-02-2013
5 | 4 | 11-03-2014
我想要的结果是:
ID | Status1 | Status2 | Status3 | Status4 | Date
----+----------+----------+----------+----------+------------
1 | 1 | | | | 01 01 2017
2 | 1 | | | | 26 04 2016
2 | | | | 4 | 20 10 2016
3 | 1 | | | | 05 11 2015
3 | | 2 | | | 20 03 2016
4 | | | | 4 | 06 06 2015
5 | 1 | | | | 10 04 2017
5 | | | 3 | | 21 12 2016
5 | | 2 | | | 25 02 2013
5 | | | | 4 | 11 03 2014
我该如何进行查询?
答案 0 :(得分:1)
您可以使用CASE
语句来实现此目的。请注意我将日期重命名为sdate,因为日期为reserved word。
CREATE TABLE myTable (id INT, status INT, [sdate] date)
INSERT INTO myTable VALUES (1, 1, '01-01-2017')
,(2, 1, '04-26-2017')
,(2, 4, '10-20-2016')
SELECT id
,CASE WHEN status = 1 then status else NULL end as status1
,CASE WHEN status = 2 then status else NULL end as status2
,CASE WHEN status = 3 then status else NULL end as status3
,CASE WHEN status = 4 then status else NULL end as status4
,sdate
FROM myTable