【问题标题】:Need help creating this aggregate SQL query [closed]需要帮助创建此聚合 SQL 查询 [关闭]
【发布时间】:2020-09-08 18:18:40
【问题描述】:

是否可以创建一个返回此结果集的 SQL 查询?

感谢您的任何建议或反馈。

【问题讨论】:

  • 建议:1) 阅读How To Ask 以提高问题的质量 2) 不要使用图片,使用格式化文本。 3) 尝试发布您的尝试。
  • 感谢Dale,下次尝试使用格式化文本,不知道有没有简单的方法可以转换Excel表格

标签: sql sql-server tsql group-by pivot


【解决方案1】:

您可以加入并进行条件聚合:

select
    b.id,
    b.name
    max(case when tib.content = 'math book'  then 'Yes' else 'No' end) has_math,
    max(case when tib.content = 'SQL book'   then 'Yes' else 'No' end) has_sql,
    max(case when tib.content = 'comic book' then 'Yes' else 'No' end) has_comic
from bag b
inner join things_in_bag tib on tib.bag_id = b.id
group by b.id, b.name

【讨论】:

  • 错误的数据库 ;)
  • @GordonLinoff:是的......已经修复了。
  • 谢谢!这正是我想要弄清楚的!
【解决方案2】:

您可以使用条件聚合:

select bag_id,
       max(case when content = 'math book' then 'Yes' else 'No' end) as has_math_book,
       max(case when content = 'SQL book' then 'Yes' else 'No' end) as has_sql_book,
       max(case when content = 'comic book' then 'Yes' else 'No' end) as has_comic_book
from things_in_bag
group by bag_id;

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多