TSQL计数在多列中出现

时间:2015-10-13 19:56:35

标签: 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

到目前为止,我到达了以下(针对q3问题),但这只是针对一个问题

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

4 个答案:

答案 0 :(得分:5)

select answer, q1, q2, q3
from
    q
    unpivot (answer for q in (q1, q2, q3)) as upvt
    pivot (count(q) for q in (q1, q2, q3)) as pvt

我犯了第一次尝试count(*)的错误,但我认为聚合必须明确地在被转动的列上,即使我认为它们在逻辑上是等价的。

答案 1 :(得分:1)

这应该有效: -

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

答案 2 :(得分:0)

如果你想要最有效的方式,我会建议在每个" 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;

这基本上使用索引来计算值,并且应该非常快,比聚合所有不重要的结果更快。

答案 3 :(得分:0)

这将有效

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;