gpt4 book ai didi

python - Sqlalchemy 真实总和

转载 作者:行者123 更新时间:2023-12-01 06:27:50 24 4
gpt4 key购买 nike

我有以下表格,想要按日期计算 true 和 group_by总和

| Date       | Value1      | Value2       |
|:-----------|------------:|:------------:|
| 2019-12-05 | 5.5 | true|
| 2019-12-05 | 4.5 | true|
| 2019-12-05 | 6.5 | false|
| 2019-12-05 | 8.5 | false|
| 2019-12-05 | 2.5 | true|
| 2019-12-06 | 3.5 | true|
| 2019-12-06 | 5.5 | true|
| 2019-12-06 | 56.5 | true|
| 2019-12-06 | 8.5 | true|
| 2019-12-06 | 99.5 | false|
| ... | ... | ... |

我通过类方法对 db.Model 进行的查询:

return db.session.query(cls.Date, func.count(cast(cls.Value2, sqlalchemy.Integer)).filter(cls.Value2== True).label("Count True Value2")) \
.group_by(cls.Date)\
.order_by("Date")

结果应该是

   | Date       | Value2     |
|:-----------|------------:|
| 2019-12-05 | 3 |
| 2019-12-06 | 4 |

编辑也不起作用

  return db.session.query(cls.Date, func.sum(case([(cls.Value2== True, 1)], else_=0).label('Value2'))) \
.filter(cls.Date== current_date.strftime("%Y-%m-%d")) \
.group_by(cls.Date)\
.order_by("Date")

最佳答案

  • 您需要将 Value2 添加到组条件中。

这是一个例子:

from datetime import date

from sqlalchemy import Integer
from sqlalchemy import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy import Column, Date, Boolean
from sqlalchemy.orm import sessionmaker

Base = declarative_base()
engine = create_engine('...creds...', echo=True)


class TestModel(Base):
__tablename__ = 'test_model'
id = Column(Integer, primary_key=True)
date = Column(Date)
value2 = Column(Boolean)


Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# a few test records
for date_ in (date(2020, 1, 1), date(2020, 1, 2)):
session.add(TestModel(date=date_, value2=True))
session.add(TestModel(date=date_, value2=True))
session.add(TestModel(date=date_, value2=True))
session.add(TestModel(date=date_, value2=False))

session.commit()

query = (
session.query(
TestModel.date,
TestModel.value2,
func.count('*').label('counter')
)
# uncomment if you need only True values
# .filter(TestModel.value2.is_(True))
.group_by(TestModel.date, TestModel.value2)
.order_by(TestModel.date)
)

for rec in query:
print('date {date}, value2 {value2}, counter {counter}'.format(
date=rec.date,
value2=rec.value2,
counter=rec.counter,
))

# date 2020-01-01, value2 True, counter 3
# date 2020-01-01, value2 False, counter 1
# date 2020-01-02, value2 False, counter 1
# date 2020-01-02, value2 True, counter 3

希望这有帮助。

关于python - Sqlalchemy 真实总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60042908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com