【问题标题】:pythonic version of SQL MAX case whenPythonic 版本的 SQL MAX 情况下
【发布时间】:2022-12-06 22:02:36
【问题描述】:

鉴于下面的代码,实现这一目标的更好的 pythonic 方法是什么。 sql语法仅供参考。 df 有很多个月的标志,但只是希望它像以往一样成为透视表。谢谢

     SELECT distinct x.ID
    ,max(case when x.Yes=1 THEN 'Yes' else null) as Yes
    ,max(case when x.No=1 THEN 'No' else null) as No
     FROM df X
     GROUP BY  x.ID

【问题讨论】:

  • 您将 python 连接到什么 RDBMS?为什么发布的 SQL 不是“pythonic”的?
  • 试图找到一种在 python 中编写这个的方法....不是 sql
  • 所以你只需要构建一个字符串?那么你打算用这个SQL字符串做什么呢?不清楚你要完成什么。
  • 如何通过 python 中的不同查询执行此数据透视组?
  • 这可能取决于 python 连接到的 RDBMS。 SQLServer 审核 sqlshack.com/python-scripts-for-pivot-tables-in-sql-server

标签: python sql


【解决方案1】:
df.groupby([id], as_index=False).agg({'Yes': 'max','No': 'max'})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    相关资源
    最近更新 更多