Get region sales along with state in SQL Server [closed]

e5njpo68  于 12个月前  发布在  SQL Server
关注(0)|答案(1)|浏览(118)

Closed. This question needs details or clarity . It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post .

Closed 5 hours ago.
Improve this question

I am new to SQL Server. I have a table with columns Region , State and Sales - like this:

RegionStateSales
EastCalifornia100
Easttexas200
Westroseland100
WestNewjerea200

I need to show region-wise sales along with state-wise sales in the same query.

Could any one please help how to do this?

g2ieeal7

g2ieeal71#

You can use rollup with group by clause like below to get region wise, state wise and total sales summary:

Query:

select region, state,sum(sales) [total sale]
from SalesData
group by region,state
  with rollup
order by region,state

Output:

regionstatetotal sale
nullnull600
Eastnull300
EastCalifornia100
EastTexas200
Westnull300
WestNewJersey200
WestRoseland100

fiddle

Or you can use window function sum()over() to get the region-wise sales like below:

Query:

select region,sum(sales)over(partition by region)[region wise total sale],state,sales
from SalesData

Output:

regionregion wise total salestatesales
East300California100
East300Texas200
West300Roseland100
West300NewJersey200

fiddle

相关问题