SQL Server uses the open window function over () to group statistics

Source: Internet
Author: User

This is a common face test, which is often used in practical projects.

Requirements: To find product categories for the group, the most expensive product information in each group.

The implementation process is as follows:

Declare @t table (ProductID   int, ProductName varchar (), ProductType varchar (), price int)  --test data Insert @t SEL  ECT 1, ' name1 ', ' P1 ', 3 union ALL Select 2, ' name2 ', ' P1 ', 5 union ALL Select 3, ' Name3 ', ' P2 ', 4 union ALL Select 4, ' Name4 ', ' P2 ', 4 --One way: Find the most expensive value in each group, and then find the price equal to this value in each group-disadvantage: To make a join select t1.* from    @t T1   Join (select ProductType,    max (Price) Price from    @t    Group by ProductType) T2 on T1. ProductType = t2. ProductType  where T1. Price = t2. Price  ORDER BY ProductType-procedure two: Use Over (), calculate the statistics, and then directly filter the result set. --over () allows the function (including aggregate functions) to be output with the line.  ; with CTE as (SELECT *, max (price) over (partition by (ProductType)) Maxprice from   @t) Select Productid,productna  Me,producttype,price from CTE where price = Maxprice  ORDER by ProductType--over () The syntax is: Over ([patition by] <order by >). It is important to note that over () is preceded by a function, and if it is an aggregate function, then order by cannot be used together. Another common scenario for--over () is for pagination with row_number ().

SQL Server uses the open window function over () to group statistics

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.