Question

I'm using this code in Microsfot Access and get the correct results:

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;

When I covert it to SQL - [Successes] + '/' + [Attempts] AS Proportion fails as invalid column names:

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;

The output looks like:

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

Can I use the columns that I have identified in SQL?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top