Summarize group by
the 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
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
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
Use to perform a summary operation rollup
on group by
the 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 all
after use , cities that do not meet the conditions will also appear, but the number of orders is zero
Note that All
can not cube
and rollup
used together, and having
used together, then All
the function will fail.
Next script:
select Ctiy,orderdate,orderid
from
SalesInfo
compute count(orderid)
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
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.