简体   繁体   English

如何在SQL中添加变量

[英]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. 此变量是布尔值,如果将其设置为True,则表示已安装该应用程序。

Example: variable = intalled apps 示例:变量=已安装的应用

In January there were 20 installed apps. 一月有20个已安装的应用程序。 In February there were 10 installed apps. 2月有10个已安装的应用程序。 In March there were 5 installed apps. 3月,安装了5个应用程序。

I want to show on the table all the apps that were installed (boolean = True): 我想在桌上显示所有已安装的应用程序(布尔值= 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? 有谁知道如何在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. 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. 希望您精通SQL,可以用所需的内容替换这些部分。

I'm assuming that you have an "Applications" table that contains an "Installed" column and an "InstalledDate" column. 我假设您有一个“应用程序”表,其中包含“已安装”列和“ InstalledDate”列。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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