TSQL计数在多列中出现的次数
我有一个表格,其中每列都是一个问题,每行都是答案,可以假设值为1到4 计算每个问题每个答案出现次数的最有效方法是什么 输入表TSQL计数在多列中出现的次数,sql,sql-server,tsql,aggregate-functions,Sql,Sql Server,Tsql,Aggregate Functions,我有一个表格,其中每列都是一个问题,每行都是答案,可以假设值为1到4 计算每个问题每个答案出现次数的最有效方法是什么 输入表 q1 q2 q3 1 3 1 2 1 4 1 2 1 期望输出表 answer q1 q2 q3 1 2 0 2 2 1 1 0 3 0 1 0 4 0 0 1 到目前为止,我得出以下结论(针对第三季度的问题),但仅针对一个问题 CREATE TA
q1 q2 q3
1 3 1
2 1 4
1 2 1
期望输出表
answer q1 q2 q3
1 2 0 2
2 1 1 0
3 0 1 0
4 0 0 1
到目前为止,我得出以下结论(针对第三季度的问题),但仅针对一个问题
CREATE TABLE #t
(
answer int
)
insert into #t (answer) values (1)
insert into #t (answer) values (2)
insert into #t (answer) values (3)
insert into #t (answer) values (4)
select * into #q3 from (select q3 as q3,count(*) as occurenceq3
from [table]
group by q3) as x
select t.answer,tb.occurenceq3 as occurenceq3
from #t t left join #q3 tb on t.answer=tb.Q3
drop table #q3
drop table #t
我犯了一个错误,第一次尝试计数(*),但我认为聚合必须显式地位于被透视的列上是有意义的,即使我认为它们在逻辑上是等价的。这应该可以:-
CREATE TABLE #question (q1 int, q2 int, q3 int)
INSERT INTO #question
VALUES
(1,3,1),
(2,1,4),
(1,2,1);
--unpivot to start with
WITH
UNPIVOTED AS
(
SELECT *
FROM
(SELECT q1,q2,q3
FROM #question) p
UNPIVOT
(answer FOR question in (q1,q2,q3)) AS unpvt
)
--Then pivot
SELECT * FROM
(SELECT answer, question FROM unpivoted) p
PIVOT
(
COUNT(question)
FOR question IN (q1,q2,q3)
) as pvt
如果您想要最有效的方法,我建议在每个“q”列上放置一个索引,并按以下方式运行查询:
select a.answer,
(select count(*) from #question q where q.q1 = a.answer) as q1,
(select count(*) from #question q where q.q2 = a.answer) as q2,
(select count(*) from #question q where q.q3 = a.answer) as q3
from (select 1 as answer union all select 2 union all select 3 union all select 4
) a;
这基本上是使用索引来计算值,并且应该非常快,比聚合所有未初始化的结果要快。这将起作用
select t1.dis,
q1=(select count(q1) from CountAnswers where q1=t1.dis),
q2=(select count(q2) from countAnswers where q2=t1.dis),
q3=(select count(q3) from countAnswers where q3=t1.dis)
from (select dis from( select q1 as dis from CountAnswers union select q2 as dis from CountAnswers union select q3 as dis from CountAnswers)mytab)t1;
可能是取消pivot,然后pivot。可能您不能引用基表目录。我试图在SQL Fiddle上运行此操作,但该网站的行为与往常一样怪异。如果您返回原始帖子并用count(q)替换count(*),查询将正常工作。不幸的是,我没有很好地将语法提交到内存中。您是对的。我刚刚编辑过。非常感谢你们两位的支持。任何我可以研究这些东西的建议。Technet有一篇文章。这一个作为介绍可能更好:
select t1.dis,
q1=(select count(q1) from CountAnswers where q1=t1.dis),
q2=(select count(q2) from countAnswers where q2=t1.dis),
q3=(select count(q3) from countAnswers where q3=t1.dis)
from (select dis from( select q1 as dis from CountAnswers union select q2 as dis from CountAnswers union select q3 as dis from CountAnswers)mytab)t1;