Summarize the usage of group by

Summarize group bythe usage with examples today .

To summarize:group by:ALL ,Cube,RollUP,Compute,Compute by

Create data script

Create Table SalesInfo
(Ctiy nvarchar(50),
OrderDate datetime,
OrderID int
)

insert into  SalesInfo
select N‘北京‘,2014-06-09,1001
union all
select N‘北京‘,2014-08-09,1002
union all
select N‘北京‘,2013-10-09,1009
union all
select N‘大连‘,2013-08-09,4001
union all
select N‘大连‘,2013-10-09,4002
union all
select N‘大连‘,2013-05-12,4003
union all
select N‘大连‘,2014-11-11,4004
union all
select N‘大连‘,2014-12-11,4005

First execute the following script:

select Ctiy,count(OrderID) as OrderCount
from
SalesInfo
group by Ctiy
with cube

Insert picture description here
You can see that the extra line is a summary of all the orders

Next script:

select Ctiy,Year(OrderDate) as OrderYear,count(OrderID) as OrderCount
from
SalesInfo
group by Ctiy,Year(OrderDate)
with cube

Insert picture description here
It can be seen that the dimensions in the grouping are summarized, and there is also a sum of orders

The next script (note that it appears rollup):

select Ctiy,Year(OrderDate) as OrderYear,count(OrderID) as OrderCount
from
SalesInfo
group by Ctiy,Year(OrderDate)
with rollup

Insert picture description here
Use to perform a summary operation rollupon group bythe first grouping field listed

Next script:

select Ctiy,count(OrderID) as OrderCount
from
SalesInfo
where
Ctiy = N‘大连‘
group by all Ctiy

We will see that group by allafter use , cities that do not meet the conditions will also appear, but the number of orders is zero

Note that Allcan not cubeand rollupused together, and havingused together, then Allthe function will fail.

Next script:

select Ctiy,orderdate,orderid
from
SalesInfo
compute count(orderid)

Insert picture description here
Two result sets are shown, one is the order result set and the other is the total number of orders result set

The last script:

select Ctiy,orderdate,orderid
from
SalesInfo
order by Ctiy
compute count(orderid) by Ctiy

Insert picture description here
According to different cities, display the order information of that city separately, and one shows the quantity of all orders in that city

Let's talk about this first.

Guess you like

Origin blog.csdn.net/WuLex/article/details/114341588