SQL SERVER Row-column Query Case When Structure for SQL SERVER Conditional Query

Keywords: SQL

1.Sql Server row-column transitions,

select  count(*) as TotalCount,SchoolId,Type,
row_number()over(order by Type asc) as RowIds
from  ALL_UserLog
group by [Type] ,SchoolId 

Query through SQL PRIVOT

    with temp as (
        select  count(*) as TotalCount,SchoolId,Type,year(AddDate) as [Year]
        from  ALL_UserLog  
        group by [Type] ,SchoolId ,year(AddDate)
    )

    select [year],SchoolId,isnull(browse,0)browse,isnull(search,0)search,isnull(Collection,0)Collection,isnull(download,0)download from temp
    pivot(
        sum(TotalCount) for Type in(browse,search,Collection,download)
    ) as m

2 SQL conditional query adopts case when structure

- Total grouping query statistics

select count(*) as TotalCount,SchoolId,[Type],
row_number() over(order by [Type] asc) as RowIds,
max(case [Type] when 'browse' then TotalCount else 0 end ) as 'browse' ,
max(case [Type] when 'search' then TotalCount else 0 end ) as 'search' ,
max(case [Type] when 'Collection' then TotalCount else 0 end ) as 'Collection' ,
max(case [Type] when 'download' then TotalCount else 0 end ) as 'download' 
from ALL_UserLog 
group by SchoolId,[Type]
order by SchoolId

- Statistics the total number of visits to a category

select Count(*) from ALL_UserLog where  Modue ='M04' and
(
     case when  AddDate between '2017-03-03'  and '2017-03-08'  then 1 else 0 end + 
     case when [Type] = 'browse' then 1 else 0 end 
 ) >= 2

The latter >= 2 satisfies at least two conditions, which can be set according to requirements.

select Count(*) from ALL_UserLog where  Modue ='M02' and
(
     case when  AddDate between '2017-03-03'  and '2017-03-08'  then 1 else 0 end + 
     case when [Type] = 'browse' then 1 else 0 end 
 ) >= 2

select Count(*) from ALL_UserLog where  Modue ='M03'  

select Count(*) from ALL_UserLog where  Modue ='M03' and
(
     case when  AddDate between '2017-03-03'  and '2017-03-08'  then 1 else 0 end + 
     case when [Type] = 'browse' then 1 else 0 end 
 ) >= 2

3. To solve the ranking problem, the order is from 11011 122 to 123 445.

For example, Chapter 1, Chapter 2, Chapter 3==, Chapter 1, Chapter 10, Chapter 11, Chapter 2, Chapter 3, etc.
String interception is adopted.
sql is as follows

select * from UM_Resource where CourseId='C0000308'
and TypeId='T4' 
order by convert(int, substring(name, charindex('The first',name)+1,charindex('chapter',name)-2))

Note that the format here is written to death, requiring the first and third characters of the text to be "Chapter 1" and "Chapter 2".
Any other good way to leave a message below is welcome. Thank you.

Posted by badgoat on Mon, 11 Feb 2019 10:21:18 -0800