V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
wuwukai007
V2EX  ›  Python

sql 求助

  •  
  •   wuwukai007 · 2021-01-19 22:35:39 +08:00 · 1485 次点击
    这是一个创建于 1164 天前的主题,其中的信息可能已经有所发展或是发生改变。

    这条 sql 是在写不出来了😔,下面是简化的表结构和条件。

    • 表一 user
    user_id username
    1 张三
    2 李四
    3 王五
    • 表二 order
    order_id user_id order_name create_time is_active shift
    1 1 001 2020-01-01 12:12:12 0 day
    2 1 001 2020-01-01 23:00:00 1 night
    3 1 002 2020-01-01 12:12:12 1 day
    4 1 002 2020-01-01 23:00:00 0 night
    • 表三 order_class
    class_id order_id sw_class
    1 1 采购
    2 2 消费
    3 2 消费
    4 3 消费
    5 4 消费
    效果:
        查询姓名为张三的订单 
        并根据订单的创建日期,班次(night,day),是否激活 is_active,作为一组条件
        统计订单所属类别(表三) sw_class 的数量
        例如 张三 在 2020-01-01 这一天,有订单
        is_activce = 1 的 且 shift = night 的 订单 为 order_id = 2
        那么类别有 class_id (2,3),消费消费 ,
        那么就有一条记录:    
        
           
    
    username is_active shift date sw_采购 sw_消费 sw_采购占订单总数比例 sw_消费占订单总数比例
    张三 1 night 2020-01-01 0 2 2/2 0/2

    结果例如:

    username is_active shift date sw_采购 sw_消费 sw_采购占订单总数比例 sw_消费占订单总数比例
    张三 0 night 2020-01-01 0 1 1/1 0/1
    张三 1 night 2020-01-01 0 2 2/2 0/2
    张三 0 day 2020-01-01 1 0 1/1 0/1
    张三 1 day 2020-01-01 0 1 0/1 1/1
    3 条回复    2021-01-20 11:57:36 +08:00
    saulshao
        1
    saulshao  
       2021-01-20 10:30:32 +08:00
    我建议你多次查询数据库,逻辑上更简单清楚
    zlowly
        2
    zlowly  
       2021-01-20 11:47:47 +08:00
    不是很看得懂你的例子,只能大概猜测是你这里可能涉及到一个行转列的查询技巧,即多行的 sw_class 转换为两列 sw_采购,sw_消费,不知这样理解对否。
    通常这种查询,如果最终列数是固定非动态的,可以用这种思路转换:

    select a,b,c,...sw as sw_采购,0 as sw_消费 from t where sw_class="采购"
    union all
    select a,b,c,...0 as sw_采购,sw as sw_消费 from t where sw_class="消费"

    然后在这个基础上在外层包装分组统计运算。
    kmonster
        3
    kmonster  
       2021-01-20 11:57:36 +08:00
    一个 sql 行转列,一般这种问题都是面试的时候吧?而且只有很 low 的公司老项目才有这种类型的 SQL 。
    现在写 SQL 基本上是越简单越好,然后再用代码去做逻辑处理,不建议联表,会有笛卡尔积问题。
    一般项目到后面都是数据层的压力比较大。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5386 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 06:02 · PVG 14:02 · LAX 23:02 · JFK 02:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.