在SQL中,您可以为WHERE表达式设置别名以简化查询吗?
示例我有
SELECT * FROM T
WHERE
(x*y<15 AND x*z > 20)
OR
(x*y>20 AND x*z < 100)
有没有办法将x * y表示为a和x * z表示为b,以便我可以将我的查询重写为
SELECT * FROM T
WHERE
(a<15 AND b>20)
OR
(a>20 AND b<100)
我在SQL服务器上
答案 0 :(得分:4)
你可以这样试试。
SELECT *
FROM
(
SELECT x, y, z, (x*y) xy, (x*z) xz
FROM T
) R
WHERE (xy < 15 AND xz > 20) OR (xy > 20 AND xz < 100)
答案 1 :(得分:2)
如果您使用的是SQL Server 2005或更高版本,则可以使用Common Table Expression:
DECLARE @myTable TABLE([x] INT, [y] INT, [z] INT)
INSERT INTO @myTable VALUES(2, 1, 1)
INSERT INTO @myTable VALUES(3, 2, 2)
INSERT INTO @myTable VALUES(4, 2, 3)
INSERT INTO @myTable VALUES(5, 2, 5)
INSERT INTO @myTable VALUES(6, 4, 5)
;WITH CTE ([x], [y], [z], [xy], [xz]) AS
(
SELECT x, y, z, x*y, x*z FROM @myTable
)
SELECT x, y, z
FROM CTE
WHERE
(xy < 15 AND xz > 20)
OR (xy > 20 AND xz < 100)
答案 2 :(得分:1)
WITH T1
AS
(
SELECT T.*,
x * y AS a,
x * z AS b
FROM T
)
SELECT * FROM T1
WHERE
(a<15 AND b>20)
OR
(a>20 AND b<100);