SQL merging tables [duplicate] - sql

This question already has answers here:
Efficiently convert rows to columns in sql server
(5 answers)
Closed 8 years ago.
I am trying to merge a few tables in order to get the output as outlined in the image below.
My issue is that I am not sure what type of joins to use to achieve that
Can someone please help me with the syntax.

You could do something like this, it's a dynamic pivot as you might add/ take away users?
CREATE TABLE #Tests (
Test_ID INT,
TestName VARCHAR(50));
INSERT INTO #Tests VALUES (1, 'SQL Test');
INSERT INTO #Tests VALUES (2, 'C# Test');
INSERT INTO #Tests VALUES (3, 'Java Test');
CREATE TABLE #Users (
[User_ID] INT,
UserName VARCHAR(50));
INSERT INTO #Users VALUES (1, 'Joe');
INSERT INTO #Users VALUES (2, 'Jack');
INSERT INTO #Users VALUES (3, 'Jane');
CREATE TABLE #UserTests (
ID INT,
[User_ID] INT,
Test_ID INT,
Completed INT);
INSERT INTO #UserTests VALUES (1, 1, 1, 0);
INSERT INTO #UserTests VALUES (2, 1, 2, 1);
INSERT INTO #UserTests VALUES (3, 1, 3, 1);
INSERT INTO #UserTests VALUES (4, 2, 1, 0);
INSERT INTO #UserTests VALUES (5, 2, 2, 0);
INSERT INTO #UserTests VALUES (6, 2, 3, 0);
INSERT INTO #UserTests VALUES (7, 3, 1, 1);
INSERT INTO #UserTests VALUES (8, 3, 2, 1);
INSERT INTO #UserTests VALUES (9, 3, 3, 1);
DECLARE #Cols VARCHAR(MAX);
SELECT #Cols = STUFF((SELECT distinct ',' + QUOTENAME(u.UserName)
FROM #Users u
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
DECLARE #Query NVARCHAR(MAX);
SELECT #Query = 'SELECT TestName, ' + #Cols + ' FROM
(
SELECT
t.TestName,
u.UserName,
ut.Completed
FROM
#Tests t
INNER JOIN #UserTests ut ON ut.Test_ID = t.Test_ID
INNER JOIN #Users u ON u.[User_ID] = ut.[User_ID]) x
PIVOT (
MAX(Completed)
FOR UserName IN (' + #Cols + ')
) AS pt';
EXEC(#Query);
Results are:
TestName Jack Jane Joe
C# Test 0 1 1
Java Test 0 1 1
SQL Test 0 1 0
(Same results as yours, but in a different sort order.)

Related

How to add pagination to this dynamic sql

I have the following table with its respective data
CREATE TABLE [dbo].[Columns]
(
[ColumnId] INT,
[TableId] INT NOT NULL,
[ColumnName] NVARCHAR(150) NOT NULL,
[Order] INT,
[Key] BIT
)
CREATE TABLE [dbo].[Tables]
(
[TableId] INT,
[TableName] NVARCHAR(200),
[DistrictId] INT
)
CREATE TABLE [dbo].[RowValues]
(
[ColumnId] INT NOT NULL,
[RowNumber] INT NOT NULL,
[Value] NVARCHAR(200) NOT NULL
)
insert into [Columns] values (1, 1, 'StudentName', 1, 1)
insert into [Columns] values (2, 1, 'Grade', 1, 0)
insert into [Columns] values (3, 1, 'Year', 1, 0)
insert into [Columns] values (4, 1, 'Section', 1, 0)
insert into [Columns] values (5, 2, 'TeacherName', 1, 1)
insert into [Columns] values (6, 2, 'Department', 1, 0)
insert into [Tables] values (1, 'Student', 1)
insert into [Tables] values (2, 'Teacher', 1)
insert into [RowValues] values (1, 1, 'Student Alan')
insert into [RowValues] values (2, 1, '99')
insert into [RowValues] values (3, 1, '1st')
insert into [RowValues] values (4, 1, 'Section 1')
insert into [RowValues] values (1, 2, 'Student Alex')
insert into [RowValues] values (2, 2, '98')
insert into [RowValues] values (3, 2, '1st')
insert into [RowValues] values (4, 2, 'Section 1')
insert into [RowValues] values (1, 3, 'Student Alfonso')
insert into [RowValues] values (2, 3, '97')
insert into [RowValues] values (3, 3, '1st')
insert into [RowValues] values (4, 3, 'Section 1')
insert into [RowValues] values (1, 4, 'Student Ben')
insert into [RowValues] values (2, 4, '96')
insert into [RowValues] values (3, 4, '1st')
insert into [RowValues] values (4, 4, 'Section 1')
insert into [RowValues] values (1, 5, 'Student Cathy')
insert into [RowValues] values (2, 5, '95')
insert into [RowValues] values (3, 5, '1st')
insert into [RowValues] values (4, 5, 'Section 1')
insert into [RowValues] values (5, 1, 'Teacher Tesso')
insert into [RowValues] values (6, 1, 'Biology Dept')
insert into [RowValues] values (5, 2, 'Teacher Marvin')
insert into [RowValues] values (6, 2, 'Math Dept')
I wanted to be able to sort the dynamic column
example sort by 'StudentName' ASC it would sort data using column returning
When sorting by StudentName:
StudentName Grade Year Section
'Student Alan' 99 '1st' 'Section 1'
'Student Alex' 98 '1st' 'Section 1'
'Student Alfonso' 97 '1st' 'Section 1'
.
.
.
When sorting by Grade ASC:
StudentName Grade Year Section
'Student Cathy' 95 '1st' 'Section 1'
'Student Ben' 96 '1st' 'Section 1'
'Student Alfonso' 97 '1st' 'Section 1'
.
.
.
When sorting by TeacherName ASC (different table)
TeacherName Department
'Teacher Marvin' 'Math Dept'
'Teacher Tesso' 'Biology Dept'
.
.
.
I have manage to accomplish this.
The problem is adding Pagination to my dynamic SQL string.
This is my stored procedure
CREATE PROCEDURE [dbo].[usp_DynamicSearch_Paged]
(#districtId INT,
#searchTerm NVARCHAR(max),
#pageNumber INT = 1,
#pageSize INT = 10,
#sortColumn NVARCHAR(20),
#sortDirection INT)
AS
BEGIN
DECLARE #columns nvarchar(max),
#sql nvarchar(max),
#rows int
SET #rows = (#pageNumber - 1) * #pageSize;
SELECT
#columns = (SELECT ',' + QUOTENAME(ColumnName)
FROM Tables AS T
INNER JOIN Columns AS C ON T.TableId = C.TableId
WHERE T.districtId = #districtId
ORDER BY C.[Order]
FOR XML PATH(''))
SELECT
#columns = (SELECT ',' + QUOTENAME(ColumnName)
FROM Tables AS T
INNER JOIN Columns AS C ON T.TableId = C.TableId
WHERE T.districtId = #districtId
ORDER BY C.[Order]
FOR XML PATH(''))
SELECT [Columns] = REPLACE(REPLACE(value,'[',''),']','')
FROM STRING_SPLIT(STUFF(#Columns, 1, 1, ''),',')
SET #sql = N'
SELECT * INTO #Fields FROM (
SELECT
ROW_NUMBER() OVER (PARTITION BY ColumnName ORDER BY (SELECT NULL)) RN,
districtId,
ColumnName
, V.[Value]
FROM Tables AS T
INNER JOIN Columns AS C
ON T.TableId = C.TableId
LEFT OUTER JOIN RowValues AS V
ON C.ColumnId = V.ColumnId
) t
PIVOT (
MIN([Value])
FOR [ColumnName]
IN ('
+ STUFF(#Columns, 1, 1, '') +
')
) AS PivotTable
DECLARE #KeyColumnName NVARCHAR(100)
SELECT #KeyColumnName = ColumnName
FROM Tables AS T
INNER JOIN Columns AS C
ON T.TableId = C.TableId
WHERE T.districtId = ' + CAST(#districtId AS VARCHAR) + '
AND C.IsKey = 1
DECLARE #sql NVARCHAR(MAX)
SET #SQL = ''
SELECT *
FROM #Fields
WHERE '' + #KeyColumnName + '' LIKE '''''+ #searchTerm +'%''''
''
OFFSET ('+CAST(#rows AS VARCHAR)+') ROWS
FETCH NEXT ' +CAST(#pageSize AS VARCHAR) +' ROWS ONLY;
EXEC sp_EXECUTESQL #sql
'
EXEC sp_executesql #sql
END
I just added the
OFFSET ('+CAST(#rows AS VARCHAR)+') ROWS
FETCH NEXT ' +CAST(#pageSize AS VARCHAR) +' ROWS ONLY;
EXEC sp_EXECUTESQL #sql
and now it doesn't work
The OFFSET and FETCH clauses are the options of the ORDER BY clause. They allow you to limit the number of rows to be returned by a query.
https://www.sqlservertutorial.net/sql-server-basics/sql-server-offset-fetch/
I think you need to declare ORDER BY

How to order by dynamic column in TSQL?

I have these tables
CREATE TABLE [dbo].[Columns]
(
[ColumnId] INT,
[TableId] INT NOT NULL,
[ColumnName] NVARCHAR(150) NOT NULL,
[Order] INT,
[Key] BIT
)
CREATE TABLE [dbo].[Tables]
(
[TableId] INT,
[TableName] NVARCHAR(200)
)
CREATE TABLE [dbo].[RowValues]
(
[ColumnId] INT NOT NULL,
[RowNumber] INT NOT NULL,
[Value] NVARCHAR(200) NOT NULL
)
With this sample data:
insert into [Columns] values (1, 1, 'StudentName', 1, 1)
insert into [Columns] values (2, 1, 'Grade', 1, 0)
insert into [Columns] values (3, 1, 'Year', 1, 0)
insert into [Columns] values (4, 1, 'Section', 1, 0)
insert into [Columns] values (5, 2, 'TeacherName', 1, 1)
insert into [Columns] values (6, 2, 'Department', 1, 0)
insert into [Tables] values (1, 'Student')
insert into [Tables] values (2, 'Teacher')
insert into [RowValues] values (1, 1, 'Student Alan')
insert into [RowValues] values (2, 1, '99')
insert into [RowValues] values (3, 1, '1st')
insert into [RowValues] values (4, 1, 'Section 1')
insert into [RowValues] values (1, 2, 'Student Alex')
insert into [RowValues] values (2, 2, '98')
insert into [RowValues] values (3, 2, '1st')
insert into [RowValues] values (4, 2, 'Section 1')
insert into [RowValues] values (1, 3, 'Student Alfonso')
insert into [RowValues] values (2, 3, '97')
insert into [RowValues] values (3, 3, '1st')
insert into [RowValues] values (4, 3, 'Section 1')
insert into [RowValues] values (1, 4, 'Student Ben')
insert into [RowValues] values (2, 4, '96')
insert into [RowValues] values (3, 4, '1st')
insert into [RowValues] values (4, 4, 'Section 1')
insert into [RowValues] values (1, 5, 'Student Cathy')
insert into [RowValues] values (2, 5, '95')
insert into [RowValues] values (3, 5, '1st')
insert into [RowValues] values (4, 5, 'Section 1')
insert into [RowValues] values (5, 1, 'Teacher Tesso')
insert into [RowValues] values (6, 1, 'Biology Dept')
insert into [RowValues] values (5, 2, 'Teacher Marvin')
insert into [RowValues] values (6, 2, 'Math Dept')
I have this stored procedure:
CREATE PROCEDURE [dbo].[usp_DynamicSearch_Paged]
(#searchTerm NVARCHAR(max),
#pageNumber INT = 1,
#pageSize INT = 10,
#sortColumn NVARCHAR(20),
#sortDirection INT)
AS
BEGIN
DECLARE #TableNameLiteral nvarchar(13) = 'TableName'
DECLARE #ColumnNameLiteral nvarchar(10) = 'ColumnName'
IF (ISNULL(#sortColumn, '') = '')
BEGIN
SET #sortColumn = #TableNameLiteral
END
;WITH KeyTableId AS
(
SELECT
T.TableId
FROM
[dbo].[Tables] T
INNER JOIN
[dbo].[Columns] C ON T.TableId = C.[TableId]
WHERE
C.[Key] = 1
), ColumnId AS
(
SELECT
[KeyValue] = C.[ColumnName]
,[ColumnId] = V.[ColumnId]
,V.[Value]
,T.[TableName]
,C.[ColumnName]
,C.[Order]
,C.[Key]
FROM
[dbo].[Tables] T
INNER JOIN
[dbo].[Columns] C ON T.TableId = C.[TableId]
LEFT JOIN
[dbo].[RowValues] V ON V.[ColumnId] = C.[ColumnId]
RIGHT JOIN
KeyTableId KT ON T.TableId = KT.TableId
)
SELECT *
FROM ColumnId
WHERE ISNULL(#SearchTerm,'') = ''
OR [Value] LIKE #SearchTerm + '%'
ORDER BY
CASE WHEN #sortDirection = 2 THEN
CASE
WHEN #sortColumn = #TableNameLiteral THEN [TableName]
WHEN #sortColumn = #ColumnNameLiteral THEN [ColumnName]
END
END DESC,
CASE WHEN #sortDirection = 1 THEN
CASE
WHEN #sortColumn = #TableNameLiteral THEN [TableName]
WHEN #sortColumn = #ColumnNameLiteral THEN [ColumnName]
END
END ASC
OFFSET ((#pageNumber - 1) * #pageSize) ROWS
FETCH NEXT #PageSize ROWS ONLY;
SELECT
ColumnId = C.ColumnId,
C.ColumnName,
C.[Order],
C.[Key]
FROM [dbo].[Tables] T
LEFT JOIN [dbo].[Columns] C ON T.TableId = C.[TableId]
END
Based on the schema you can probably understand what I am trying to build.
My question is how do I order the result based on dynamic name
example (order by "StudentName" DESC)
Expected output
KeyValue ColumnId Value TableName ColumnName Order Key
'StudentName' 1 'Student Cathy' 'Student' 'StudentName' 1 1
'StudentName' 1 'Student Ben' 'Student' 'StudentName' 2 1
'StudentName' 1 'Student Alfonso' 'Student' 'StudentName' 3 1
'StudentName' 1 'Student Alex' 'Student' 'StudentName' 4 1
'StudentName' 1 'Student Alan' 'Student' 'StudentName' 5 1
'Grade' 2 '99' 'Student' 'Grade' 5 0 (Alan's Grade)
'Grade' 2 '98' 'Student' 'Grade' 4 0
... Year
... Section
...
How Do I sort by StudentName or Grade or Section or Year if key = student name
or
Sort by TeacherName or department if key = Teachername
indicated by #sortColumn NVARCHAR(20),
example
declare #SearchTerm NVARCHAR(max)=''
declare #pageNumber INT = 1
declare #pageSize INT = 10
declare #sortColumn NVARCHAR(20) ='StudentName'
declare #sortDirection int= 1 -- 0 asc 1 desc
exec [usp_DynamicSearch_Paged] #SearchTerm, #pageNumber, #pageSize, #sortColumn, #sortDirection

SQL Server: stored procedure using recursive CTE finding values matching a total

I need to find within a stored procedure which values match a wanted total following valex's solution recursive query in SQL Server
The following works pretty well assuming the CTE anchor recordset is very small
CREATE TABLE #t ([id] INT, [num] FLOAT);
DECLARE #wanted FLOAT = 100000
INSERT INTO #t ([id], [num])
VALUES (1, 17000), (2, 33000), (3, 53000), (4, 47000), (5, 10000),
(6, 53000), (7, 7000), (8, 10000), (9, 20000), (10, 5000),
(11, 40000), (12, 30000), (13, 10000), (14, 8000), (15, 8000),
(16, 10000), (17, 74000)
/* when you add more records the query becomes too slow, remove this comment
to test*/
/*,(18,10000),(19,78000),(20,10000),(21,10000),(22,80000),(23,19000),
(24,8000),(25,5000),(26,10000),(27,4000),(28,46000),(29,48000),(30,20000),
(31,10000),(32,25000),(33,10000),(34,13000),(35,16000),(36,10000),
(37,5000), 38,5000),(39,30000),(40,15000),(41,10000)*/
;
CREATE NONCLUSTERED INDEX [idx_id] ON #t ([id]);
WITH CTE AS
(
SELECT
id, num AS CSum,
CAST(id AS VARCHAR(MAX)) AS path
FROM
#t
WHERE num <= #wanted
UNION ALL
SELECT
#t.id, #t.num + CTE.CSum AS CSum,
CTE.path + ',' + CAST(#t.id AS VARCHAR(MAX)) AS path
FROM
#T
INNER JOIN
CTE ON #T.num + CTE.CSum <= #wanted AND CTE.id < #T.id
WHERE
#T.num + CTE.CSum <= #wanted
)
SELECT TOP 1 Path
FROM CTE
WHERE CTE.CSum = #wanted
ORDER BY id
DROP TABLE #t
It will return 3,4 which are the first 2 rows whose [num] values gives the #wanted total.
This works reasonably fast when there are just a few records in the temp table #t but when you remove the comment and all remaining records (from id 17 to id 41) the query just takes forever because the CTE grows exponentially.
Is there a way to speed up the code? i just need the first matching total (the list anchor dataset is ordered so a result like 3,4 is better than 8,20,22)
What if you took an iterative approach? This would be pretty simple to give the ability to stop as soon as a solution is found.
This was put together quickly, so you may can optimize further. I tested for your example (ran in less than 1 second) and several other combinations and levels of depth.
Result Depth Total IdList NumList
------ ----------- ----------- ---------- -------------
Found 1 100000 3,4 53000,47000
Full Code:
-- Configuration
DECLARE #wanted FLOAT = 100000
DECLARE #MaxDepth INT = 10 -- Customize how many levels you want to look
SET NOCOUNT ON
IF OBJECT_ID('tempdb..#T') IS NOT NULL DROP TABLE #T
IF OBJECT_ID('tempdb..#T') IS NULL BEGIN
CREATE TABLE #T (Id INT, Num INT)
INSERT INTO #t ([id], [num])
VALUES (1, 17000), (2, 33000), (3, 53000), (4, 47000), (5, 10000),
(6, 53000), (7, 7000), (8, 10000), (9, 20000), (10, 5000),
(11, 40000), (12, 30000), (13, 10000), (14, 8000), (15, 8000),
(16, 10000), (17, 74000)
CREATE NONCLUSTERED INDEX [idx_id] ON #t ([id]);
END
-- Setup processing table
IF OBJECT_ID('tempdb..#U') IS NOT NULL DROP TABLE #U
CREATE TABLE #U (
MaxId INT,
Total INT,
IdList VARCHAR(MAX),
NumList VARCHAR(MAX)
)
-- Initial population from source table
INSERT #U
SELECT Id, Num,
CONVERT(VARCHAR(10), Id),
CONVERT(VARCHAR(10), Num)
FROM #T
-- Iterative approach
DECLARE #Depth INT = 0
WHILE NOT EXISTS (SELECT * FROM #U WHERE Total = #wanted) BEGIN
-- Increment depth
SET #Depth = #Depth + 1
IF #Depth >= #MaxDepth BEGIN
PRINT 'Max depth reached'
RETURN -- Stop processing further
END
-- Calculate sum for this depth
IF OBJECT_ID('tempdb..#V') IS NOT NULL
DROP TABLE #V
SELECT
T.Id AS MaxId,
U.Total + T.Num AS Total,
U.IdList + ',' + CONVERT(VARCHAR(10), T.Id) AS IdList,
U.NumList + ',' + CONVERT(VARCHAR(10), T.Num) AS NumList
INTO #V
FROM #U U
INNER JOIN #T T
ON U.MaxId < T.Id
-- Replace data for next iteration
TRUNCATE TABLE #U
INSERT #U
SELECT * FROM #V
-- Check if no more combinations available
IF ##ROWCOUNT = 0 BEGIN
PRINT 'All combinations tested'
RETURN -- Stop processing further
END
END
-- Return result
SELECT TOP 1 'Found' AS [Result], #Depth AS Depth, Total, IdList, NumList FROM #U WHERE Total = #wanted

Why isn't STUFF and FOR XML PATH not concenating?

I have these two tables
CREATE TABLE [dbo].[Things](
[testid] [int] NOT NULL,
[testdesc] [varchar](10) NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[ThingsStaging](
[otherid] [int] NOT NULL,
[testid] [int] NOT NULL
) ON [PRIMARY]
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (1, N'Stuff')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (2, N'Things')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (3, N'Orcs')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (4, N'Grubs')
INSERT INTO [dbo].[Things] ([testid], [testdesc]) VALUES (5, N'Shrooms')
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 1)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 2)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (1, 3)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (2, 3)
INSERT INTO [dbo].[ThingsStaging] ([otherid], [testid]) VALUES (2, 4)
;with allThings(otherid, descs)
as
(
select ts.otherid ,
stuff ((select ', ' + blah.testdesc as [text()]
from (
select distinct t.testdesc
from Things as t
where t.testid = ts.testid ) as blah
for xml path('')), 1, 1, '') as stuffs
from ThingsStaging as ts
)
select *
from allThings
Now when run this query, I get
otherid stuffs
1 Stuff
1 Things
1 Orcs
2 Orcs
2 Grubs
But I should get:
otherid stuffs
1 Stuff, Things, Orcs
2 Orcs, Grubs
I'm not understanding what I'm doing wrong.
I understand what I did wrong. Code will explain better.
select otherid, stuff((select ', ' + t.testdesc as [text()]
from Things as t
inner join ThingsStaging as its on t.testid = its.testid
where its.otherid = ts.otherid
for xml path('')), 1, 1, '') as descs
from ThingsStaging as ts
group by otherid

SQL Statement(s)

If I have the following table:
CREATE TABLE #temp (
id int,
num int,
question varchar(50),
qversion int );
INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);
SELECT *
FROM #temp;
DROP TABLE #temp;
And I would like to get a table to display the three questions in their lastest version? This is in SQL Server 2005
CREATE TABLE #temp (
id int,
num int,
question varchar(50),
qversion int );
INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);
WITH latest AS (
SELECT num, MAX(qversion) AS qversion
FROM #temp
GROUP BY num
)
SELECT #temp.*
FROM #temp
INNER JOIN latest
ON latest.num = #temp.num
AND latest.qversion = #temp.qversion;
DROP TABLE #temp;
SELECT t1.id, t1.num, t1.question, t1.qversion
FROM #temp t1
LEFT OUTER JOIN #temp t2
ON (t1.num = t2.num AND t1.qversion < t2.qversion)
GROUP BY t1.id, t1.num, t1.question, t1.qversion
HAVING COUNT(*) < 3;
You're using SQL Server 2005, so it's worth at least exploring the over clause:
select
*
from
(select *, max(qversion) over (partition by num) as maxVersion from #temp) s
where
s.qversion = s.maxVersion
I would like to get a table to display the three latest versions of each question.
I assume that that qversion is increasing with time. If this assumption is backwards, remove the desc keyword from the answer.
The table definition does not have an explicit not null constraint on qversion. I assume that a null qversion should be excluded. (Note: Depending on settings, lack of an explicit null/not null in the declaration may result in a not null constraint.) If the table does have a not null contraint, than the text where qversion is not null should be removed. If qversion can be null, and nulls need to be included in the result set, then additional changes will need to be made.
CREATE TABLE #temp (
id int,
num int,
question varchar(50),
qversion int );
INSERT INTO #temp VALUES(1, 1, 'Question 1 v1', 1);
INSERT INTO #temp VALUES(2, 1, 'Question 1 v2', 2);
INSERT INTO #temp VALUES(3, 2, 'Question 2 v1', 1);
INSERT INTO #temp VALUES(4, 2, 'Question 2 v2', 2);
INSERT INTO #temp VALUES(5, 2, 'Question 2 v3', 3);
INSERT INTO #temp VALUES(7, 2, 'Question 2 v4', 4);
-- ^^ Added so at least one row would be excluded.
INSERT INTO #temp VALUES(6, 3, 'Question 3 v1', 1);
INSERT INTO #temp VALUES(8, 4, 'Question 4 v?', null);
select id, num, question, qversion
from (select *,
row_number() over (partition by num order by qversion desc) as RN
from #temp
where qversion is not null) T
where RN <= 3