SQL SERVER 條件查詢 Case When結構
阿新 • • 發佈:2019-01-30
1.Sql Server 行轉列 ,
select count(*) as TotalCount,SchoolId,Type,
row_number()over(order by Type asc) as RowIds
from ALL_UserLog
group by [Type] ,SchoolId
通過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(瀏覽,0)瀏覽,isnull(搜尋,0)搜尋,isnull(收藏,0)收藏,isnull(下載,0)下載 from temp
pivot(
sum(TotalCount) for Type in(瀏覽,搜尋,收藏,下載)
) as m
2 SQL 條件查詢採用case when結構
–分組查詢統計總數
select count(*) as TotalCount,SchoolId,[Type],
row_number() over(order by [Type] asc) as RowIds,
max(case [Type] when '瀏覽' then TotalCount else 0 end ) as '瀏覽' ,
max(case [Type] when '搜尋' then TotalCount else 0 end ) as '搜尋' ,
max(case [Type] when '收藏' then TotalCount else 0 end ) as '收藏' ,
max(case [Type] when '下載' then TotalCount else 0 end ) as '下載'
from ALL_UserLog
group by SchoolId,[Type]
order by SchoolId
–統計某個類別的訪問總數
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] = '瀏覽' then 1 else 0 end
) >= 2
–後面>=2 是至少滿足兩個條件,這個可以根據需求來設定
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] = '瀏覽' 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] = '瀏覽' then 1 else 0 end
) >= 2
3.解決排序問題 1 2 3 4 5 ,,,, 是從1 10 11 12 2 到 1 2 3 4 5 的順序。
比如第1章 第2章 第3章 ==》》第1章 第10章 第11章 第2章 第3章等問題。
採用字串擷取的方式。
sql 如下
select * from UM_Resource where CourseId='C0000308'
and TypeId='T4'
order by convert(int, substring(name, charindex('第',name)+1,charindex('章',name)-2))
注意這裡的格式寫死了 要求文字的第一個第三個字元 必須是 “第” 跟 ”章“ 。
有什麼其他好的方式歡迎在下面留言。謝謝大家。