SQL Server:在查询中将数据检索到变量以查询查询内容

时间:2011-12-20 09:50:54

标签: sql-server

我有一个T-SQL大查询:

SELECT ( ... some big subquery ... ), 
  ( ... some big subquery ... ) / field1, 
  CASE WHEN ( ... some big subquery ... ) = 0 THEN ... ELSE ... END
FROM table
WHERE ( ... some big subquery ... ) IS NOT NULL

有没有办法以mysql方式实现:

SELECT @big_query_result := ( ... some big subquery ... ), 
  @big_query_result / field1, 
  CASE WHEN @big_query_result = 0 THEN ... ELSE ... END
FROM table
WHERE @big_query_result IS NOT NULL

2 个答案:

答案 0 :(得分:2)

使用Common Table表达式:

;WITH CTE_Results AS
(
SELECT ID, (SOME BIG SUB QUERY) AS SubResult FROM table
)
SELECT 
RES.SubResult
, RES.SubResult/TBL.field1
, CASE WHEN RES.SubResult = 0 THEN... ELSE ... END AS FieldName
FROM table TBL
INNER JOIN CTE_Results RES
ON TBL.ID = RES.ID
WHERE RES.SubResult IS NOT NULL

答案 1 :(得分:0)

您可以使用子查询为“大查询”提供别名,例如:

select  BigQueryResult
,       BigQueryResult / field1
,       case when BigQueryResult = 0 then ... else ... end
from    (
        select   ( ... some big subquery ... ) as BigQueryResult
        ,        ... other columns ...
        from     table
        ) as SubQueryAlias