Please convert this excel formula to tsql:…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
Please convert this excel formula to tsql: "=IF(COUNTA(AE2:AO2)=COUNTIF(AE2:AO2,"-1"),"NO TESTS",((100/11)+100)/(COUNTA(AE2:AO2,)-COUNTIF(A2:AE2,"-1"))*COUNTIF(AE2:AO2,"1"))"
- Assistant
The equivalent T-SQL code for the given Excel formula would be:
sqlDECLARE @count_ae2_to_ao2 INT = (SELECT COUNT(*) FROM (VALUES (AE2), (AF2), (AG2), (AH2), (AI2), (AJ2), (AK2), (AL2), (AM2), (AN2), (AO2)) AS t(val) WHERE val <> -1); DECLARE @count_one INT = (SELECT COUNT(*) FROM (VALUES (AE2), (AF2), (AG2), (AH2), (AI2), (AJ2), (AK2), (AL2), (AM2), (AN2), (AO2)) AS t(val) WHERE val = 1); IF (@count_ae2_to_ao2 = (SELECT COUNT(*) FROM (VALUES (AE2), (AF2), (AG2), (AH2), (AI2), (AJ2), (AK2), (AL2), (AM2), (AN2), (AO2)) AS t(val) WHERE val = -1)) BEGIN SELECT 'NO TESTS'; END ELSE BEGIN SELECT ((100 / 11) + 100) / (@count_ae2_to_ao2) * @count_one; ENDNote that this code assumes that the values in the
AE2toAO2range are stored in separate columns in a table in the database. The code uses a derived table to simulate the range of values, and and functions are implemented using with a conditional clause in the statement. - User
Rewrite it using temporary tables instead
- Assistant
Sure, here's a version of the code that uses temporary tables instead:
sqlDECLARE @count_ae2_to_ao2 INT; DECLARE @count_one INT; CREATE TABLE #temp (val INT); INSERT INTO #temp (val) VALUES (AE2), (AF2), (AG2), (AH2), (AI2), (AJ2), (AK2), (AL2), (AM2), (AN2), (AO2); SET @count_ae2_to_ao2 = (SELECT COUNT(*) FROM #temp WHERE val <> -1); SET @count_one = (SELECT COUNT(*) FROM #temp WHERE val = 1); IF (@count_ae2_to_ao2 = (SELECT COUNT(*) FROM #temp WHERE val = -1)) BEGIN SELECT 'NO TESTS'; END ELSE BEGIN SELECT ((100 / 11) + 100) / (@count_ae2_to_ao2) * @count_one; END DROP TABLE #temp;In this code, the temporary table
#tempis created to store the values from theAE2toAO2range. TheCOUNTandCOUNTIFfunctions are performed on this temporary table, and the result is stored in the variables@count_ae2_to_ao2and@count_one. The rest of the code is the same as the previous version.