求教一个sql交叉查询的语句或思路,感谢各位关心 20
table例子如下:A列B列1223311312......求一个语句实现统计出来A列=1且B列=2的数量,A列=2且B列=3的数量,A列=3且B列=1的数量....最后...
table例子如下:
A列 B列
1 2
2 3
3 1
1 3
1 2
... ...
求一个语句实现统计出来 A列=1且B列=2的数量,A列=2且B列=3的数量,A列=3且B列=1的数量....
最后形成交叉表结果如下:
1 2 3
1 0 2 1
2 0 0 1
3 1 0 0
例子中AB列的值只列举了123,其实现实中会有若干数量不定的值
再次拜谢各位了 展开
A列 B列
1 2
2 3
3 1
1 3
1 2
... ...
求一个语句实现统计出来 A列=1且B列=2的数量,A列=2且B列=3的数量,A列=3且B列=1的数量....
最后形成交叉表结果如下:
1 2 3
1 0 2 1
2 0 0 1
3 1 0 0
例子中AB列的值只列举了123,其实现实中会有若干数量不定的值
再次拜谢各位了 展开
4个回答
展开全部
这个你要使用动态SQL。使用透视图方式。如果是别的数据库 需要使用大量的 case when 方式
组合,不如使用程序控制。
---
如下是sql server 2005
create table RawData
(
A int,
B int
)
insert into RawData
select 1,2 union all
select 2,3 union all
select 3,1 union all
select 1,3 union all
select 1,2
--主检索下方。
declare @ClmH nvarchar(MAX)
select @ClmH = COALESCE(@ClmH + ',[' + cast(CH as varchar) + ']','[' + cast(CH as varchar)+ ']')
from
(
select distinct B as CH from RawData
) A order by A.CH
declare @PivotSQL nvarchar(MAX)
set @PivotSQL=N'select A,'+@ClmH+' from RawData pivot
(
count(B) for [B] in ('+@ClmH+')
) as PVT'
EXECUTE(@PivotSQL)
---------
执行结果:
A 1 2 3
----------------------
1 0 2 1
2 0 0 1
3 1 0 0
组合,不如使用程序控制。
---
如下是sql server 2005
create table RawData
(
A int,
B int
)
insert into RawData
select 1,2 union all
select 2,3 union all
select 3,1 union all
select 1,3 union all
select 1,2
--主检索下方。
declare @ClmH nvarchar(MAX)
select @ClmH = COALESCE(@ClmH + ',[' + cast(CH as varchar) + ']','[' + cast(CH as varchar)+ ']')
from
(
select distinct B as CH from RawData
) A order by A.CH
declare @PivotSQL nvarchar(MAX)
set @PivotSQL=N'select A,'+@ClmH+' from RawData pivot
(
count(B) for [B] in ('+@ClmH+')
) as PVT'
EXECUTE(@PivotSQL)
---------
执行结果:
A 1 2 3
----------------------
1 0 2 1
2 0 0 1
3 1 0 0
展开全部
select sum(case when a=1 and b=2 then 1 else 0 end),sum(case when a=2 and b=3 then 1 else 0 end),sum(case when a=3 and b=1 then 1 else 0 end)
from table
from table
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select
(select count(*) from table where A=2 and B=3) as a,
(select count(*) from table where A=3 and B=1) as b,
(select count(*) from table where A=1 and B=2) as c
from table
(select count(*) from table where A=2 and B=3) as a,
(select count(*) from table where A=3 and B=1) as b,
(select count(*) from table where A=1 and B=2) as c
from table
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select
(select count(*) from table where A=2 and B=3) as a,
(select count(*) from table where A=3 and B=1) as b,
(select count(*) from table where A=1 and B=2) as c
from table
(select count(*) from table where A=2 and B=3) as a,
(select count(*) from table where A=3 and B=1) as b,
(select count(*) from table where A=1 and B=2) as c
from table
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询