我正在尝试查找最近7天内的百分比增长,但是我有点卡住了。当前,在我创建的SQL查询中,您可以获取过去7天中新帐户的总数。但是现在,如何改进才能以百分比形式返回结果?
这是到目前为止完成的SQL查询。
谢谢
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
答案 0 :(得分:0)
您可以创建一个包含两列的临时表,例如“旧计数”和“新计数”。使用从SELECT查询中获得的值填充表。 然后,从临时表中检索值以计算百分比差异并删除临时表。
答案 1 :(得分:0)
您可以尝试以下方式计算最近7天的计数,然后在7天之前计算所有数字,然后计算百分比
select max(last7days_count) as last7days_count,
max(before7days_count) as before7days_count,
((max(before7days_count)*1.00)/max(last7days_count))*100.00 as percentage from
(
SELECT COUNT(DISTINCT account_type) as last7days_count, 0 as before7days_count
FROM account
WHERE date_created > NOW() - INTERVAL 7 DAY
union all
SELECT 0 as last7days_count COUNT(DISTINCT account_type) as before7days_count
FROM account
WHERE date_created < NOW() - INTERVAL 7 DAY
) as T
答案 2 :(得分:0)
为了在一个查询中全部运行,您可以考虑下一个查询:
SELECT
/* Count for previous period. */
beforeCount,
/* Count for current period. */
afterCount,
/* Simple math, just calculating percentage. */
(beforeCount * 100) / afterCount AS percent
FROM (
SELECT
/* Select count for previous period. */
(
SELECT COUNT(DISTINCT account_type)
FROM account
WHERE date_created BETWEEN NOW() - INTERVAL 14 DAY AND NOW() - INTERVAL 7 DAY
) AS beforeCount,
/* Select count for current period. */
(
SELECT COUNT(DISTINCT account_type)
FROM account
WHERE date_created > NOW() - INTERVAL 7 DAY
) AS afterCount
) AS tmp
答案 3 :(得分:0)
有条件的聚合可能有效。使用CASE
仅计算新帐户,使用SELECT count(DISINCT CASE
WHEN date_created > NOW() - INTERVAL 7 DAY THEN
account_type
END)
/
count(DISTINCT CASE
WHEN date_created <= NOW() - INTERVAL 7 DAY THEN
account_type
END)
* 100 increase
FROM account;
仅计算旧帐户。
Sub EraseTheThings()
Dim shp As Shape
For Each shp In ActiveSheet.Shapes
shp.Delete
Next
End Sub
答案 4 :(得分:0)
使用临时表,您可以像这样:
create temporary table storeCount IF NOT EXISTS (
oldCount INT(10) not null,
newCount INT(10) not null
);
insert into percentage (oldCount,newCount)
values
(SELECT COUNT(DISTINCT acc1.account_type)FROM account acc1, SELECT COUNT(DISTINCT acc2.account_type)
FROM account acc2 WHERE acc2.date_created > NOW() - INTERVAL 7 DAY);
select ((newCount/oldCount)*100) as percentage from storeCount;
drop temporary table IF EXISTS storeCount;
答案 5 :(得分:0)
假设每个帐户有一行,则不需要distinct
。我猜你想要:
SELECT (SUM(date_created >= CURDATE() - INTERVAL 7 DAY) * 100/
SUM(date_created > CURDATE() - INTERVAL 7 DAY)
) as percent_increase
FROM account