-1

I am working on a SQL query and I need to do a calculation and store the result in dummy column in the output.

select NodeID, 
           count(distinct cpuindex) as number_of_cpu, 
           case 
               when count(distinct cpuindex) < 8 THEN 1
               else count(distinct cpuindex) / 8 
           end AS number_of_cores
    --number_of_cpu*number_of_cores*0.5 as Dummy_Column
    from CPUMultiLoad_Daily 
    where nodeid in (select nodeid from nodesdata)
    group by NodeID

I am doing the calculation as shown above however I am still missing something. Any help will be greatly appreciated.

Dale K
  • 25,246
  • 15
  • 42
  • 71
SQL Novice
  • 193
  • 8
  • 2
    You cannot re-use a column alias in the same `select` where it is defined You need to repeat the expression, use a CTE, or use a subquery. – Gordon Linoff Jul 20 '20 at 21:11
  • 2
    What do you mean by missing something? What should it be doing and what isn't it doing? Sample data and expected results would help. – Dale K Jul 20 '20 at 21:11

2 Answers2

2

Below the correct query using a CTE.

;with CTE as (
     select NodeID, 
         count(distinct cpuindex) as number_of_cpu, 
          case 
               when count(distinct cpuindex) < 8 THEN 1
          else count(distinct cpuindex) / 8 
          end AS number_of_cores
     from CPUMultiLoad_Daily 
     where nodeid in (select nodeid from nodesdata)
     group by NodeID
)
select *, number_of_cpu*number_of_cores*0.5 as  Dummy_Column
from CTE
Gabriele Franco
  • 879
  • 6
  • 10
2

SQL doesn't allow for you to do computation on data being computed in the same query. As there is already an example with a CTE, here is what the subquery version might look like...

SELECT *, number_of_cpu*number_of_cores*0.5 as  Dummy_Column 
FROM (select NodeID, 
         count(distinct cpuindex) as number_of_cpu, 
          case 
               when count(distinct cpuindex) < 8 THEN 1
          else count(distinct cpuindex) / 8 
          end AS number_of_cores
     from CPUMultiLoad_Daily 
     where nodeid in (select nodeid from nodesdata)
     group by NodeID)

There are pros/cons between CTE and Subquery methods that you might consider depending on your specific case. You can read about it here Difference between CTE and SubQuery?

Nik Srinivas
  • 163
  • 5
  • Thank you, I was able to update my query as you mentioned. Is it able to display the output as Integer and not decimal? – SQL Novice Jul 21 '20 at 19:28