有什么办法可以避免子查询?

我在TEST表中有以下示例数据:

CREATE TABLE TEST(
f1 varchar(50) NULL,
f2 varchar(50) NULL,
flag int NULL);

INSERT INTO [test]([f1],[f2],[flag]) VALUES('P','a',1);
INSERT INTO [test]([f1],[f2],[flag]) VALUES('P','b',0);
INSERT INTO [test]([f1],[f2],[flag]) VALUES('Q','c',1);
INSERT INTO [test]([f1],[f2],[flag]) VALUES('Q','d',0);
INSERT INTO [test]([f1],[f2],[flag]) VALUES('R','e',1);
INSERT INTO [test]([f1],[f2],[flag]) VALUES('S','f',0);

我想要这个结果:

f1  f2whenFlagIs1   f2whenFlagIs0
P   a               b
Q   c               d
R   e               NULL
S   NULL            f

以下查询已被写入以获得相同的结果:

SELECT isnull(test1.f1,test0.f1) f1, test1.f2 f2whenFlagIs1 , test0.f2 AS f2whenFlagIs0
FROM 
(select * from test where flag = 1) AS test1  full JOIN
(select * from test where flag = 0) AS test0 
ON test1.f1 = test0.f1

有什么办法可以避免子查询?


给定样本数据,假设每个f1 + flag组合只能有一个值,这里有两种方法:

SELECT f1, 
  f2WhenFlagIs1 = MAX(CASE WHEN flag = 1 THEN f2 END),
  f2WhenFlagIs0 = MAX(CASE WHEN flag = 0 THEN f2 END)
FROM dbo.TEST
GROUP BY f1;

要么

SELECT f1, f2WhenFlagIs1 = [1], f2WhenFlagIs0 = [0]
FROM dbo.TEST AS t
PIVOT (MAX(f2) FOR flag IN ([0],[1])) AS p;

如果您对任何给定的f1flag对可以有多个值,则需要更好地定义所需的结果。

链接地址: http://www.djcxy.com/p/18547.html

上一篇: Is there any way to avoid sub queries?

下一篇: Calculate left positioning in div jquery