如何使用已定义的表获取我所需的记录
Posted
技术标签:
【中文标题】如何使用已定义的表获取我所需的记录【英文标题】:How to get my required record with defined table 【发布时间】:2018-11-16 11:59:56 【问题描述】:您好,我的表结构如下所示
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
【问题讨论】:
张贴图片最好是复制/粘贴文件信息。你能做到吗? @jalazbe 我已更新,请查看 【参考方案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
【讨论】:
【参考方案2】: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
以下是Yogesh Sharma给出的答案的更新
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
【讨论】:
【参考方案3】:您可以将roll up
与聚合一起使用:
select questionid, Response, count(*)
from table t
group by questionid, Response with roll up;
【讨论】:
不,它没有按照我的需要填充记录,我只需要 2 行,即行标签和响应计数 @miteshjain。 . .我知道那不一样,但你应该知道excel
SQL Server
。 SQL Server
是数据库工具而不是数据呈现工具。以上是关于如何使用已定义的表获取我所需的记录的主要内容,如果未能解决你的问题,请参考以下文章
如果在 django 中使用多个数据库,如何仅迁移所需的模型表