Group by issue in SQL Server 2008?

时间:2015-09-14 15:33:08

标签: sql sql-server-2008

I want to group my records without aggregate function. I have tried so far but does not work.

select   c.CustomerName, c.CustAddress, c.Phone,o.OrderDate,s.CreditEndDate 
from customer c 
inner join Orders o on c.ID=o.CustomerID
inner join Sales s on s.OrderID = o.OrderNum   
group by c.CustomerName

Because the data needs to be grouped:(Before group by)

+---------+----------+------+------------+------------+
| Halima  | Tegbared | 0917 | 2014-06-19 | 2015-09-05 |
+---------+----------+------+------------+------------+
| Halima  | Tegbared | 0917 | 2014-06-19 | 2015-09-07 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-07 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-07 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-09 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-09 | 2015-09-07 |
| onetime | xx       | xx   | 2015-09-07 | 2015-09-07 |
| onetime | xx       | xx   | 2015-09-07 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-09 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-09 | 2015-09-07 |
| Jemila  | Salimiya | +96  | 2015-09-09 | 2015-09-07 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-08 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-08 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-08 |
| Halima  | Tegbared | 0917 | 2015-09-05 | 2015-09-08 |
+---------+----------+------+------------+------------+

Any help? Thanks in Advance.

it shows error

Column 'customer.CustAddress' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

In this case I don't need any aggregate function just grouping the same record into one row.

1 个答案:

答案 0 :(得分:1)

A group by clause is usually used with one or more aggregate function such as sum() or count() etc.

The only time when it can be used without an aggregate function is when you don't want to duplicate values in the result set, which is equivalent to using DISTINCT keywork. In this case, you need to include all columns in the select statement in the group by.