这是我的sql
select count(type), type
from tasks
group by type
这里有4行。
count(type) type
8 Trial
7 New
3 Service
4 Uninstall
如何在一行中获得结果
Trial New Service Uninstall
8 7 3 4
我知道必须自己加入桌子。但我无法准确得到。
以下是样本表数据
id type date
1 New 2017-10-07
2 Trial 2017-10-01
3 New 2017-10-02
4 Uninstall 2017-10-05
5 Trial 2017-10-06
6 Trial 2017-10-07
答案 0 :(得分:1)
SELECT MAX(CASE WHEN type = 'Trial' THEN count_type END) as Trial,
MAX(CASE WHEN type = 'New' THEN count_type END) as New,
MAX(CASE WHEN type = 'Service' THEN count_type END) as Service,
MAX(CASE WHEN type = 'Uninstall' THEN count_type END) as Uninstall
FROM (select count(type) as count_type , type
from tasks
group by type) T
答案 1 :(得分:1)
这是通过条件聚合完成的:
SUM
在MySQL中, true为1且false为0,因此我们可以使用from datetime import timedelta
from django.db import migrations, models
import django.utils.timezone
# noinspection PyUnusedLocal
def set_free_credits_added_on(apps, schema_editor):
# noinspection PyPep8Naming
UserProfile = apps.get_model('core', 'UserProfile')
for user_profile in UserProfile.objects.all():
user_profile.free_credits_added_on = user_profile.next_billing - timedelta(days=30)
user_profile.save()
# noinspection PyUnusedLocal
def do_nothing(apps, schema_editor):
pass
class Migration(migrations.Migration):
dependencies = [
('core', '0078_auto_20171104_0659'),
]
operations = [
migrations.AddField(
model_name='userprofile',
name='free_credits_added_on',
# This default value is overridden in the following data migration code
field=models.DateTimeField(
auto_now_add=True,
default=django.utils.timezone.now,
verbose_name='Free Credits Added On'
),
preserve_default=False,
),
migrations.RunPython(code=set_free_credits_added_on, reverse_code=do_nothing),
]
来计算匹配。