I have the following data in a SQL table
Temp table variable @RndQuesnCount
contains this data,
Recid conceptID MinDisplayCount
1 3839 2
2 4802 3
Question table : QuesTable
QuesCompID Ques_ConceptDtlID
88 4802
89 4802
90 4802
91 4802
92 4802
93 4802
What I would like to show is the min display count for question which is in @RndQuesnCount
for the concept id, so now the data should come as below
QuesCompID Ques_ConceptDtlID
88 4802
89 4802
90 4802
because conceptid
(4802) has min display count 3 in @RndQuesnCount
table.
Can anyone help me to solve this problem ?
Example - Using TOP PERCENT keywordSELECT TOP(10) PERCENT contact_id, last_name, first_name FROM contacts WHERE last_name = 'Anderson' ORDER BY contact_id; This SQL SELECT TOP example would select the first 10% of the records from the full result set.
To select first 10 elements from a database using SQL ORDER BY clause with LIMIT 10. Insert some records in the table using insert command. Display all records from the table using select statement.
There is no difference between EXISTS with SELECT * and SELECT 1. SQL Server generates similar execution plans in both scenarios. EXISTS returns true if the subquery returns one or more records. Even if it returns NULL or 1/0.
Simple use of ROW_NUMBER()
and a join gets the results, I think. Data setup:
declare @RndQuesnCount table (recid int,conceptid int,mindisplaycount int)
insert into @RndQuesnCount(Recid,conceptID,MinDisplayCount) values
(1, 3839, 2),
(2, 4802, 3)
declare @QuesTable table (QuesCompID int,Ques_ConceptDtlID int)
insert into @QuesTable(QuesCompID,Ques_ConceptDtlID) values
(88, 4802),
(89, 4802),
(90, 4802),
(91, 4802),
(92, 4802),
(93, 4802)
Query:
select
t.rn,
t.QuesCompID,
t.Ques_ConceptDtlID
from
@RndQuesnCount rqc
inner join
(select *,ROW_NUMBER() OVER (PARTITION BY Ques_ConceptDtlID ORDER BY QuesCompID) rn from @QuesTable) t
on
rqc.conceptID = t.Ques_ConceptDtlID and
rqc.MinDisplayCount >= t.rn
Results:
rn QuesCompID Ques_ConceptDtlID
-------------------- ----------- -----------------
1 88 4802
2 89 4802
3 90 4802
try:
declare @RndQuesnCount int;
select @RndQuesnCount=MinDisplayCount
from table_variable where conceptID=4802;
set rowcount @RndQuesnCount;
select * from QuesTable;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With