【问题标题】:how to write query for multiple columns in select and in group by only 1 column如何编写查询中的多列 select 和 group by only 1 column
【发布时间】:2012-06-30 06:43:11
【问题描述】:

我有一个问题

select t1.id,t1.col1,t1.col2,t2.col1,t2.col2,sum(t2.col3) as total
From table1 t1
join table2 t2 on t1.id=t2.id
where t1.col =@col
Group by t1.id

它给了我一个错误

t1.col1 在选择列表中无效,因为它不包含在 聚合函数或 GROUP BY 子句。

如何在group by子句中选择多列单列?

【问题讨论】:

    标签: sql sql-server


    【解决方案1】:

    您不能在Group By 子句中选择多列和一列,除非您将它们放在某个组函数中,例如AVG, MIN , MAX 等,或者您在 Group BY 子句本身中添加所有列。

      select t1.id,t1.col1,t1.col2,t2.col1,t2.col2,sum(t2.col3) as total
       From table1 t1
       join table2 t2 on t1.id=t2.id
       where t1.col =@col
       Group by t1.id , ,t1.col1,t1.col2,t2.col1,t2.col2
    

    【讨论】:

    • 我只需要在 group by 中取单列。结果应仅按 col1 分组
    • @Himanshu,如果选择列表中的其他列没有变化的值,将它们添加到Group By不会影响结果。
    • 如果 col1=id 和 col2=name 并且如果我在 id 分组后像 {group by id,name} 一样,它会再次为 name 创建一个组吗?我认为是的,它会根据 group by 子句中的列生成所有可能的组对吗?
    • @Himanshu,虽然不看数据就不可能说些什么,但恕我直言,您可以在列上相应地使用聚合函数,例如,如果您使用 MIN(name) 并从 @987654328 中省略 name 列@ 子句,它不会生效。
    【解决方案2】:

    如果 t1.col1,t1.col2,t2.col1,t2.col2 是数字列,您可以使用 min, max。 对于字符串列,您需要在 groupby 语句中使用它们

    【讨论】:

      猜你喜欢
      • 2020-08-15
      • 2021-12-30
      • 1970-01-01
      • 2020-01-19
      • 2013-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-04
      相关资源
      最近更新 更多