简体   繁体   中英

How to add variables in SQL

I have a variable that I need to show it by month. This variable is a boolean and if its set True, it means that the app was installed.

Example: variable = intalled apps

In January there were 20 installed apps. In February there were 10 installed apps. In March there were 5 installed apps.

I want to show on the table all the apps that were installed (boolean = True):

January: 20

February: 20 (January) + 10 =  30

March: 20 (January) + 10 (February) + 5 (March) = 35

Does anyone know how I could do this in Mysql?

Thanks

You could use a subquery to group installations by month. Then you can us a variable in the outer query to calculate the cumulative sum:

select  installation_year
,       installation_month
,       installation_count
,       (@running_sum:= @running_sum + installation_count) as cumulative_sum
from    (
        select  year(installation_date) as installation_year
        ,       month(installation_date) as installation_month
        ,       count(*) as installation_count
        from    YourTable
        group by
                installation_year
        ,       installation_month
        ) as SubQueryAlias
join    (select @running_sum := 0) as InitVars
order by 
        installation_year
,       installation_month

Example at SQL Fiddle.

something like:

Select COUNT(*),Month 
From Apps
where installed = true
group by Month

If I understand correctly, it's just a simple query with an order by.

select COLUMNS_YOU_WANT from TABLE_NAME 
where YOUR_BOOLEAN == True 
order by SOME_DATE_COLUMN

Hopefully you're proficient enough in SQL to replace the sections with what you need.

I'm assuming that you have an "Applications" table that contains an "Installed" column and an "InstalledDate" column. If so...

SELECT Count(*)
FROM   Applications
WHERE  Installed = 1 -- Assumes a bit/boolean column.
AND    InstalledDate BETWEEN @StartDate AND @EndDate;

Scott

I GOT IT! I used the recursive

SELECT (select id_time from database.dim_time where id_time = a.fk_time) AS yearmonth, (select sum( if( installed in (1), 1,0)) as installed from database.facts_table where fk_time <= yearmonth ) as installed FROM database.facts_table AS a GROUP BY yearmonth ORDER BY yearmonth ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM