通过识别列名称在SQL中使用MS Access代码

时间:2014-02-27 16:43:29

标签: sql sql-server case iif

我在Microsfot Access中使用此代码并获得正确的结果:

SELECT tbl_Test.generate_query AS Query Name, 
       Sum(IIf([RecNum] Is Not Null,1,0)) AS Attempts, 
       Sum(IIf([Query_test]='Yes',1,0)) AS Successes, 
       Sum(IIf([Query_test]='No',1,0)) AS Failures, 
       [Successes] & "/" & [Attempts] AS SuccessProportion
       FROM tbl_Test
       GROUP BY tbl_Test.generate_query
       ORDER BY tbl_Test.generate_query;

当我将其转换为SQL时,[Successes] + '/' + [Attempts] AS Proportion作为无效列名失败:

SELECT generate_query AS Query_Name, 
       sum(case when RecNum is NOT NULL then 1 else 0 end) AS Attempts, 
       sum(case when Query_test = 'Yes' then 1 else 0 end) AS Successes,
       sum(case when Query_test = 'No' then 1 else 0 end) AS Failures,
       [Successes]  + '/'  +  [Attempts] AS Proportion
       FROM tbl_TPF 
       GROUP BY generate_query 
       ORDER BY generate_query;

输出如下:

Query Name           Attempts        Successes      Failures    SuccessProportion
First Query             1               0               1               0/1
Second Query            1               0               1               0/1
Third Query             2               1               1               1/2
Fourth Query            1               1               0               1/1
Fifth Query             1               0               1               0/1
Sixth Query             1               0               1               0/1

我可以使用我在SQL中识别的列吗?

1 个答案:

答案 0 :(得分:1)

SELECT  Q.Query_Name
       ,Q.Attempts
       ,Q.Successes
       ,Q.Failures
       ,CAST(Q.[Successes] AS NVARCHAR(10)) + '/' + CAST(Q.[Attempts] AS NVARCHAR(10)) AS Proportion
FROM (
SELECT generate_query AS Query_Name, 
       sum(case when RecNum is NOT NULL then 1 else 0 end) AS Attempts, 
       sum(case when Query_test = 'Yes' then 1 else 0 end) AS Successes,
       sum(case when Query_test = 'No' then 1 else 0 end) AS Failures
       FROM tbl_TPF 
       GROUP BY generate_query 
     )Q
ORDER BY Q.Query_Name