Sqlserver displays columns not involved in GROUP BY clause in SELECT statement

Insert image description here

In SQL Server, if you group certain columns in the GROUP BY clause, but want to display other columns that are not involved in the SELECT statement, you can use aggregate functions and subqueries to achieve this. This can be done by getting the required aggregate values ​​in the GROUP BY subquery and selecting the other columns in the outer query. Here is an example:

Suppose you have a table named with columns Orderssuch as OrderID, CustomerID, OrderDateand and you want to group by and display the earliest order date for each customer along with the total order amount.TotalAmountCustomerID

SELECT
    o.CustomerID,
    MIN(o.OrderDate) AS EarliestOrderDate,
    SUM(o.TotalAmount) AS TotalOrderAmount
FROM
    Orders o
GROUP BY
    o.CustomerID;

The above query will CustomerIDgroup by and display the earliest order date and total order amount in the SELECT statement CustomerID.

If you also want to display other customer-related information (for example CustomerName), you can use a subquery:

SELECT
    o.CustomerID,
    c.CustomerName,
    MIN(o.OrderDate) AS EarliestOrderDate,
    SUM(o.TotalAmount) AS TotalOrderAmount
FROM
    Orders o
INNER JOIN
    Customers c ON o.CustomerID = c.CustomerID
GROUP BY
    o.CustomerID, c.CustomerName;

In this query, we related Ordersthe tables through an inner join (INNER JOIN) Customersand selected the columns in the SELECT statement CustomerNameto display CustomerIDthe CustomerNameearliest order date and total order amount.

This way you can perform aggregation operations in the GROUP BY clause while displaying other columns that are not involved in the SELECT statement. Depending on your data model and needs, you can tailor the query appropriately to meet your requirements.

Guess you like

Origin blog.csdn.net/weixin_45626288/article/details/132701647