用于创建没有聚合函数的新列的SQL查询

时间:2014-03-03 16:09:26

标签: sql sql-server tsql

我的表格数据

LOCATION GROUP  FUNCTION STATUS
L1         G1       F1   0
L1         G1       F1   1
L1         G1       F1   1
L1         G1       F2   1
L1         G1       F2   0
L1         G1       F2   0
L1         G1       F3   1
L1         G1       F3   0
L1         G1       F3   1

我想要的输出

LOCATION GROUP F1   F2  F3
L1        G1   0    1   1
L1        G1   1    0   0
L1        G1   1    0   1

我尝试使用Select CASE但它不起作用

谢谢你。

1 个答案:

答案 0 :(得分:0)

它没有给出确切的结果,但我们可以像这样经历

DECLARE @amount TABLE (LOCATION  VARCHAR(10),GROUPS VARCHAR(10),FUNCTIONS VARCHAR(10),Status INT)

INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F1',0)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F1',1)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F1',1)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F2',1)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F2',0)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F2',0)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F3',0)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F3',0)
INSERT INTo @amount (LOCATION,GROUPS,FUNCTIONS,Status)VALUES ('L1','G1','F3',1)

select LOCATION,GROUPS,Function1,Function2,Function3   from
(Select location,GROUPS,Status,FUNCTIONS from @amount) t
PIVOT (MAX(Status)FOR FUNCTIONS IN ([Function1],[Function2],[Function3]))AS p