如何在SQL中添加变量

时间:2013-03-05 19:26:53

标签: mysql sql

我有一个变量,我需要按月显示它。此变量是布尔值,如果其设置为True,则表示已安装该应用程序。

实施例: 变量=安装的应用程序

1月份已安装了20个应用。 2月份安装了10个应用程序。 3月份安装了5个应用程序。

我想在桌面上显示已安装的所有应用程序(boolean = True):

January: 20

February: 20 (January) + 10 =  30

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

有谁知道我怎么能在Mysql中做到这一点?

由于

5 个答案:

答案 0 :(得分:1)

您可以使用子查询按月对安装进行分组。然后你可以在外部查询中使用一个变量来计算累积和:

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.

答案 1 :(得分:1)

类似的东西:

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

答案 2 :(得分:0)

如果我理解正确,那只是一个带有订单的简单查询。

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

希望你在SQL中足够熟练,用你需要的东西替换这些部分。

答案 3 :(得分:0)

我假设您有一个“应用程序”表,其中包含“已安装”列和“已安装日期”列。如果是的话......

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

斯科特

答案 4 :(得分:0)

我知道了!我用了递归

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