如何使用定义的 table 获取我需要的记录

How to get my required record with defined table

你好我的table结构如下

enter image description here

并使用 sql 查询,我想将其设为以下结构格式

enter image description here

我必须使用单个 sql 查询来完成此操作。

目前我用 excel 功能做了这个 我能得到什么建议吗?

Questionid  Response        Response
   1        HighlyEngaged   HighlyEngaged
   2        VeryPrepared    VeryPrepared
   2        VeryPrepared1   VeryPrepared1

 to

 RowLabels        Count of Response
  1                1
  HighlyEngaged    1
  2                2 
  VeryPrepared     1
  VeryPrepared1    1

您可以将 roll up 与聚合一起使用:

select questionid, Response, count(*)
from table t  
group by questionid, Response with roll up;
drop table #teee
CREATE TABLE #teee
    ([Questionid] int, [Response] varchar(13), [Response1] varchar(13))
;

INSERT INTO #teee
    ([Questionid], [Response], [Response1])
VALUES
    (1, 'HighlyEngaged', 'HighlyEngaged'),
    (2, 'VeryPrepared', 'VeryPrepared'),
    (2, 'VeryPrepared1', 'VeryPrepared1')
;

select res,cnt from (select [Questionid],cast([Questionid]as varchar(100)) res ,count([Response]) cnt from #teee
group by [Questionid]
union all
select [Questionid],cast([Response]as varchar(100)) res,count([Response]) r1 from #teee
group by [Questionid],[Response])a
order by [Questionid],res

以下是对

给出的答案的更新
select isnull([Response],[Questionid]),total from (select [Questionid], [Response], count(*) total
from #teee t  
group by [Questionid], [Response] with rollup) a
where  isnull([Response],[Questionid]) is not null
order by [Questionid],1 

我准备了以下查询,我认为它可以帮助你:

DROP TABLE QA
GO
CREATE TABLE QA
(
    Questionid  INT
    ,Response   VARCHAR(100) 
)

INSERT INTO QA
    VALUES(1,'HighlyEngaged')
   ,(2,'VeryPrepared' )
   ,(5,'Asked' )
   ,(5,'Priority' )
   ,(5,'Explained' )
   ,(8,'Yes' )
   ,(9,'Set Agenda' )
   ,(9,'Take Atten' )
   ,(11,'Assigned')
   ,(11,'Individual')
   ,(12,'Predict')
   ,(12,'Questions')

SELECT
    CASE
        WHEN Response = '' THEN CAST(QuestionId AS VARCHAR)
        ELSE ''
    END QId
   ,Response
   ,ResponseTotal
FROM (SELECT
        QuestionId
       ,'' Response
       ,COUNT(Response) ResponseTotal
    FROM QA
    GROUP BY QuestionId
    UNION ALL
    SELECT
        QuestionId
       ,Response
       ,COUNT(1)
    FROM QA
    GROUP BY QuestionId
            ,Response) a
ORDER BY QuestionId, CASE
    WHEN Response = '' THEN 0
    ELSE 1
END