Home > database >  Transfer line column
Transfer line column

Time:10-09

Figure a data table, I want to query no. 1 to 3, zhang SAN's income details, the effect is shown in figure 2
Could you tell me how to write SQL statements to?

CodePudding user response:

The test data
 -If not object_id (N 'Tempdb for.. # T ') is null 
Drop table # T
Go
The Create table # T ([name] nvarchar (22), Date [Date], [revenue] int)
Insert # T
Select N 'zhang', '2019-1-1', 500 union all
Select N 'zhang', '2019-1-2', 400 union all
Select N 'zhang', '2019-1-3', 300 union all
Select N 'zhang', '2019-1-4', 500 union all
Select N 'zhang', '2019-1-5', 500 union all
Select N 'zhang', '2019-1-6', 600
Go
- the end of the test data
DECLARE @ SQL VARCHAR (MAX)
The SET @ SQL='the select [name]'
SELECT SQL + SQL=@ @ ', the sum (case [date] the when "' + RTRIM (date)
+ "' then [revenue] else 0 end) [' + RTRIM (date) + '] '
The FROM (SELECT DISTINCT
Date
The FROM # T WHERE date BETWEEN '2019-1-1' AND '2019-1-3 s'
) a
SQL=SET @ @ SQL
+ ', the sum ([revenue]) subtotals from # T WHERE date BETWEEN ' ' '2019-1-1' AND ', '2019-1-3' 'group by [name]'
The EXEC (@ SQL)


  • Related