3

我有一个 sql 视图。示例如下。问题是我想使用所有字段,但我不想按每个字段分组。我该如何规避呢?我只需要在 fieldA 上分组,而不是其他人……实际上与其他人分组会弄乱我想看到的数据。我正在使用 SQL Server 2008。谢谢!

select 
fieldA,
fieldB,
fieldC,
fieldD,
....
from my_table as a join other_table b on a.id=b.id
group by fieldA, fieldB, fieldC, fieldD
4

4 回答 4

10

通常,当我想选择多个字段并仅基于其中一个字段聚合某些内容时,我将在派生表中执行聚合并加入要从中选择的表,如下所示:

select fieldA, thingYouWantToAggregate, fieldB, fieldC, fieldD
from my_table
inner join
(
    select fieldA, thingYouWantToAggregate
    from my_table
    group by fieldA

) rsAggregated on rsAggregated.fieldA = my_table.fieldA
于 2012-07-20T19:07:13.103 回答
3

您需要对不想包含在分组依据的列使用聚合函数。我通常使用min

select 
  fieldA,
  min(fieldB),
  min(fieldC),
  min(fieldD),
....
from my_table as a join other_table b on a.id=b.id
group by fieldA
于 2012-07-20T18:58:59.913 回答
1

我真的不明白你在找什么,但我不妨把它扔在那里....

select distinct fieldA, ....
from table_name
于 2012-07-20T20:27:13.743 回答
-1
select 
  o.Customer, count(*) as ItemCount
from 
  Orders o
inner join 
  OrderDetails od on o.OrderID = od.OrderID
group by 
  o.Customer
于 2017-05-18T06:44:31.820 回答