Does SQL allow assigning the return of an aggregate function to another variable of the same type? I’m trying to take the Count(ID) of a table and assign the returned result to a temp table and my query continues to error with an ‘aggregate function error’ so I’m wondering if the return value of COUNT(ID) is able to be assigned to a variable?
SELECT Count(ID) From SomeTable
DECLARE @ttl INT
SET @ttl = Count(ID)
I’d like to take this returned number, let’s say 500, and then assign it to an INT variable in a temp table
DECLARE @cnt INT = 0;
DECLARE @startYear DATETIME = '2011-01-01 00:00:00.000'
DECLARE @endYear DATETIME = '2011-12-31 23:59:59.999'
DECLARE @ttl INT
SELECT DATEPART(year, @startYear) AS [Year of Totals], COUNT(ID) AS [Total For Year], GETDATE() AS [DATE/TIME of RUN]
FROM SomeTable
ORDER BY [Year of Totals]
SET @cnt = @cnt + 1;
SET @startYear = DATEADD(year, 1, @startYear);
SET @endYear = DATEADD(year, 1, @endYear);
SET @ttl = COUNT(ID); --> Problem Points to this as Invalid column 'ID'
INSERT INTO TempYearlyResults (Year, Total_YEAR, Date_Time, Test_Data) VALUES (DATEADD(YEAR,-1, @startYear), @ttl, GETDATE(), 'Is this working')
Editing original post with more details - Pic For Reference:
--Pseudocode BEGIN
-- Variable Declarations
-- Initialize counter to zero
--> EDIT this for the start year
--> EDIT this for that end of start year
-- Initialize for Total Counts for Year
-- Create A Temp Table to Drop Loop Data into
--WHILE the counter is less than the number of years being requested, run the following WHILE LOOP WHILE @cnt < 3 --> EDIT this for the complete number of years being requested BEGIN
-- SELECT the Year, Total Count for said Year, and Date/Time this run is being executed
-- Increment the counter to display the next year in the loop
-- Increment the Start Year to the next year
-- Increment the end of the start year
-- Set @ttl Variable equal to the Total For Year of each year
-- Populate the Temp Table with the results
-- Show the collected results in the Temp Table
-- Drop Table after populating to allow for creation next time
-- Pseudocode END