sql-server - SQL Pivot on multiple columns
问题描述
I have a query where I am pulling odds and football results:
SELECT
Div, BookieResult, COUNT(BookieResult) AS WinLossCount, OddsCategory
FROM
[dbo].[MatchOutcomes]
GROUP BY
div, OddsCategory, BookieResult
This returns a result like this:
I'm looking to get results where the data is more readable and each like is on a single line like:
I've been trying to pivot the data in many different ways but cant seem to get it in SQL. does anyone know if the layout above can be accomplished?
Thanks.
解决方案
;WITH Table AS
(
Select Div, BookieResult, Count(BookieResult) as WinLossCount,
OddsCategory
FROM [dbo].[MatchOutcomes]
group by div, OddsCategory, BookieResult
)
select Res1.Div
,Res1.[Loss]
,Res1.[Win]
,Res1.[oddscategory]
,Res2.[Loss]
,Res2.[Win]
,Res2.[oddscategory]
,Res3.[Loss]
,Res3.[Win]
,Res3.[oddscategory]
,Res4.[Loss]
,Res4.[Win]
,Res4.[oddscategory]
from
(
select Div
,[Loss]
,[Win]
,[oddscategory]
from Table
pivot
(
max(winlosscount)
for BookResult IN ([Loose],[Win])
)Rs1
where oddscategory = 0
)Res1
LEFT JOIN
(
select Div
,[Loss]
,[Win]
,[oddscategory]
from Table
pivot
(
max(winlosscount)
for BookResult IN ([Loose],[Win])
)Rs2
where oddscategory = 1
)Res2 ON Res2.Div = Res1.Div
LEFT JOIN
(
select Div
,[Loss]
,[Win]
,[oddscategory]
from Table
pivot
(
max(winlosscount)
for BookResult IN ([Loose],[Win])
)Rs3
where oddscategory = 2
)Res3 Res3.Div = Res1.Div
LEFT JOIN
(
select Div
,[Loss]
,[Win]
,[oddscategory]
from Table
pivot
(
max(winlosscount)
for BookResult IN ([Loose],[Win])
)Rs4
where oddscategory = 3
)Res4 Res4.Div = Res1.Div
推荐阅读
- github - 如何在 Github 中恢复个人访问令牌?
- transactions - 通过静态属性线程挂起 SqlAzureExecutionStrategy 安全吗?
- wordpress - 如何在静态页面中使用 elementor“产品图片”小部件?
- sql - 在 SQL 输出中查找 XML 元素的每个实例
- javascript - 当我开始输入消息时节点服务器一直关闭
- java - 如何删除固定数组中的元素
- python - 新近度和频率分割
- transform - Skimage/LAB-变换和灰度图像
- c# - 为什么我从 asp.net mvc 的下拉选择器中获取空值?我已将 IQueryable 用于下拉菜单
- react-native - 错误:找不到屏幕“入职”的“组件”、“getComponent”或“儿童”道具。如果您传递了“未定义”,则可能会发生这种情况