I want to get alternate series of records using SQL Server.
For example :
I want to skip first 10 records (1 to 10) in sequence and get other 10 records (11 to 20) after that I want to skip next 10 records (21 to 30) and get another next 10 records (31 to 40)
I have done for alternate rows as below...
SELECT ROW, EmployeeID
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY EmployeeID) AS ROW, *
FROM Employee) A
WHERE
ROW % 2 = 0
But in case of my requirement above logic will not work. Please help me to make above thing works..
Linq will also accepted
Thanks
SELECT ROW, EmployeeID
FROM
(SELECT
ROW_NUMBER() OVER (ORDER BY EmployeeID) AS ROW, *
FROM Employee) A
WHERE
((ROW - 1)/10) % 2 = 1
I have done above of your requirement like below (Example).
Generated 1200 number sequentially from 1 to 1200 like below
;WITH CTE
AS
(
SELECT 1 PERIOD_SID
UNION ALL
SELECT PERIOD_SID+1 FROM CTE WHERE PERIOD_SID<1200
)
SELECT * INTO #PERIOD1 FROM CTE
OPTION(MAXRECURSION 0)
After this i have find alternative numbers like you have mentioned in your query
SELECT PERIOD_SID FROM
(
SELECT CASE
WHEN PERIOD_SID%10 <> 0 THEN PERIOD_SID / 10
WHEN PERIOD_SID%10 = 0 THEN ( PERIOD_SID / 10 ) - 1
END RNO,
PERIOD_SID
FROM #PERIOD1 )A
WHERE RNO%2=0
so if you have sequential numbers in your query (If you dont have generate using rownumber) then apply above logic.
Your query need to convert like below.
SELECT EMPLOYEEID
FROM (SELECT Row_number()
OVER (
ORDER BY EMPLOYEEID)AS ROW,
*
FROM EMPLOYEE) A
WHERE ( CASE
WHEN RNO%10 <> 0 THEN RNO / 10
WHEN RNO%10 = 0 THEN ( RNO / 10 ) - 1
END )%2 = 0
may be you can try this
SELECT ROW, EmployeeID FROM(
SELECT ROW_NUMBER()OVER (ORDER BY EmployeeID)AS ROW,* FROM Employee)
A WHERE ((ROW - (ROW%10))/10) % 2 = 1
Don't if this works or not coz I dont have sql server to run. Please show the error/result after running this query.
Ask if any doubt.
Related
I need to create a sql query to analyze the atendimetos employee
My goal with this query and create a graph showing the total minutes called : how many were up 120minutes (very service time ) and
how many were below 120minutes ( normal calls ) put to use in the chart in C#
The easiest way would be to result in two columns am I right?
How can I do that ? I am unable to think of a solution.
SELECT SUM(CallDuration)
FROM CallsFromCustomers
WHERE DATE(CallDate) Between'2015-06-01' And '2015-06-31'
AND CallDuration < 120
UNION
SELECT
SUM(CallDuration)
FROM CallsFromCustomers
WHERE DATE(CallDate) Between '2015-06-01' And '2015-06-31'
AND CallDuration >= 120
Result
SUM(CallDuration)|
5584 |
759 |
SELECT
(SELECT COUNT(*)
FROM CallsFromCustomers
WHERE DATE(CallDate) Between'2015-06-01' And '2015-06-31'
AND CallDuration < 120) AS ShortCalls,
(SELECT COUNT(*)
FROM CallsFromCustomers
WHERE DATE(CallDate) Between '2015-06-01' And '2015-06-31'
AND CallDuration >= 120) AS LongCalls
I have a problem, in example: I have a range of ids of integers (from 1 to 1000), this range supposed to be ids in a SQL Server table, and I want to detect which numbers of this range are not in the table, and sorry for my bad english, thank you
another simpler option would be to use the following query
SELECT number
FROM master..spt_values
WHERE number BETWEEN 1 AND 1000
AND NOT EXISTS ( SELECT 1
FROM Your_Table t --<-- your table where you are checking
WHERE t.ID = number) -- the missing values
GROUP BY number
The above solution is only good if you are looking for around 1000 values. For more values you would need to modify it little bit, something like
-- Select the maximum number or IDs you want to check
DECLARE #Max_Num INT = 10000;
;WITH CTE AS
(
SELECT TOP (#Max_Num) ROW_NUMBER() OVER ( ORDER BY (SELECT NULL)) numbers
FROM master..spt_values v1 cross join master..spt_values v2
)
SELECT c.numbers
FROM CTE c
WHERE NOT EXISTS (SELECT 1
FROM Your_table t
WHERE t.ID = c.numbers)
One way to find "holes" is to generate a list of all possible values and then look for the ones that aren't there. If you can survive with a list of a missing value and then the number of subsequent values following it, you can do this with another method.
SQL Server 2012+ supports lead() and lag(). The following gets almost everything, except for initial missing values:
select t.id + 1 as missingid,
(coalesce(t.nextid, 1000) - t.id - 1) as nummissing
from (select t.*, lead(t.id) over (order by t.id) as nextid
from table t
t.id between 1 and 1000
) t
where t.nextid > t.id + 1 or
(t.nextid is null and t.id <> 1000)
You can get these with a little piece of special logic:
select (case when t.previd is null then 1
else t.id + 1
end) as missingid,
(case when t.previd is null then t.id - 1
else (coalesce(t.nextid, 1000) - t.id - 1)
end) as nummissing
from (select t.*, lead(t.id) over (order by t.id) as nextid,
lag(t.id) over (order by t.id) as previd
from table t
where t.id between 1 and 1000 and
) t
where (t.nextid > t.id + 1 or
(t.nextid is null and t.id <> 1000)
(t.previd is null and t.id <> 1)
)
This sounds like one of the many scenarios where it is helpful to have a numbers table:
SELECT *
FROM lkp_Numbers a
WHERE NOT EXISTS (SELECT 1
FROM YourTable b
WHERE a.num = b.Id)
AND num <= 1000
I use this to create a numbers table:
DROP TABLE lkp_Numbers
DECLARE #RunDate datetime
SET #RunDate=GETDATE()
SELECT TOP 1000 IDENTITY(int,1,1) AS Num
INTO lkp_Numbers
FROM sys.objects s1, sys.objects s2, sys.objects s3
ALTER TABLE lkp_Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Num)
That method for creating a numbers table was found here: What is the best way to create and populate a numbers table?
price c_melli cost_teacher
150000 5099572650 1
170000 5099572650 1
170000 5099572650 1
150000 0015601218 1
170000 0015601218 1
200000 0015601218 1
200000 0015601218 2
200000 0015601218 2
200000 0015601218 1
select * from
(select * from temp) as s
PIVOT
(
SUM(price)
FOR [cost_teacher] IN ([1],[2],[3])
) as p1
result is:
c_melli 1 2 3
0015601218 720000 400000 NULL
5099572650 490000 NULL NULL
I want to add column with count of 1 and 2 and 3
and add column with sum of each row
and add a row to end for calculate each columns.
Please help me.
Select t.c_melli, s.[1], c.[1], s.[2], c.[2], s[3], c.[3], s.[1]+s.[2]+s.[3] as sumRow from (select distinct c_Melli from temp) t
inner join(
select * from
(select * from temp) as s
PIVOT
(
SUM(price)
FOR [cost_teacher] IN ([1],[2],[3])
) as p1
) s on s.mellicode = t.mellicode
inner join(
select * from
(select * from temp) as s
PIVOT
(
Count(price)
FOR [cost_teacher] IN ([1],[2],[3])
) as p1
) c on c.mellicode = t.mellicode
I usually advise that people do their summary lines in the reporting tool or web page or wherever the data is going. It's too easy to get the total line mixed in with the detail lines if the record order isn't rigidly defined.
But what you want is possible, and here's a way to do it:
;
-- Turning the original query into a CTE allows us to easily re-use it in the query
with detail as (
select c_melli
, [1]
, [2]
, [3]
from
(select * from temp) as s
PIVOT
(
SUM(price)
FOR [cost_teacher] IN ([1],[2],[3])
) as p1
)
-- The first SELECT retrieves the detail pivoted row, plus a calculated total of all columns.
select c_melli
, [1]
, [2]
, [3]
, row_total = COALESCE([1],0) + COALESCE([2],0) + COALESCE([3],0)
from detail
-- using "union all" rather than "union" because "union all" skips the
-- duplicate-removal step (which we don't need) and is therefore faster.
union all
-- The section SELECT summarizes all of the detail rows.
select 'total' -- this assumes c_melli is a string; if not, use something else
, SUM([1])
, SUM([2])
, SUM([3])
, SUM(COALESCE([1],0) + COALESCE([2],0) + COALESCE([3],0))
from detail
Disclaimer: I did this from memory and have not tested it.
How about using WITH ROLLUP?
SELECT CASE WHEN (GROUPING(c_melli) = 1) THEN 'Total'
ELSE ISNULL(c_melli, 'UNKNOWN')
END as c_melli,
[1], [2], [3], [1]+[2]+[3] as Total
FROM
(select * from temp) as s
PIVOT
(
SUM(price)
FOR [cost_teacher] IN ([1],[2],[3])
) as p1
GROUP BY c_melli WITH ROLLUP
I have this table in SQL Server:
ID | videoid | title
=========================
1 | id1 | title1
2 | id2 | title2
3 | id3 | title3
And I want to create select method that search in the title row with:
SELECT * FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
And I'm looking for something like Limit in MySQL that from the SELECT results I will be able to get the 0-20,21-40,41-60 results.
Any help with this query?
I tried to use LIMIT 0, 10 and I received this error:
Could not find stored procedure 'LIMIT'.
You need to use TOP N with SQL SERVER.
SELECT TOP 10 * FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
ORDER BY SomeColumn -- Specify your column for ordering
See: TOP (Transact-SQL)
Limits the rows returned in a query result set to a specified number
of rows or percentage of rows in SQL Server
Also look under Best Practices in docs.
In a SELECT statement, always use an ORDER BY clause with the TOP
clause. This is the only way to predictably indicate which rows are
affected by TOP.
If you are looking for Paging records then you will need ROW_NUMBER
In SQL Server 2012 a new feature was introduced that provides this functionality.
Look at the OFFSET part of the ORDER BY clause
SELECT *
FROM your_table
ORDER
BY some_column
OFFSET 20 ROWS
FETCH NEXT 10 ROWS ONLY
This will return the results 20-30 of your resultset (ordered by some_column)
For SQL Server 2005 - 2008R2 you can use windowed functions to perform the same action:
SELECT *
FROM (
SELECT *
, Row_Number() OVER (ORDER BY some_column) As sequence
FROM your_table
) As a_subquery
WHERE sequence >= 20
AND sequence <= 30
For versions of SQL Server prior to SQL Server 2005 there is no efficient way of achieving this effect. Here's something that does the trick:
SELECT *
FROM (
SELECT *
, (
SELECT Count(*)
FROM your_table As x
WHERE x.some_column <= your_table.some_column
) As sequence
FROM your_table
) As a_subquery
WHERE sequence >= 20
AND sequence <= 30
Final notes: for your results to be deterministic some_column should be unique. If it isn't then you need to add extra column(s) in to the equation to provide a deterministic sort order for your sequence.
Also note that SELECT * ... should be avoided in all production code. Don't be lazy [like I was in this answer ;-)] - list out only the columns required.
There's no equivalent in T-SQL. TOP allows you to get only the first x results from the result set. You can use a trick. Using ROW_NUMBER you can add a new column that starts from 1 and is incremented automatically.
Like this:
SELECT ROW_NUMBER OVER (SomeExpression), Field FROM ...
Then you can use
SELECT TOP x FROM
(
SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber > Y ORDER BY RowNumber ASC
The trick is that this numbering is independent of the other fields, so using the same filter you'll always get the same RowNumbers and thus can filter again. This mimicks what LIMIT does.
For example, to get the entries 1 - 9 entries, you'd write:
SELECT TOP 9 FROM
(
SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber >= 1 ORDER BY RowNumber ASC
Next Page:
SELECT TOP 9 FROM
(
SELECT ROW_NUMBER OVER (ORDER BY ID) AS RowNumber, ID, videoid, title FROM ...
) tmp
WHERE RowNumber >= 10 ORDER BY RowNumber ASC
Use Top:
SELECT TOP 1 * FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
When TOP is used in conjunction with the ORDER BY clause, the result set is limited to the first N number of ordered rows; otherwise, it returns the first N number of rows in an undefined order.
Read more here.
To get results like 10-20, use ROW_NUMBER:
SELECT TOP 10 * FROM
(SELECT ROW_NUMBER() OVER (id_field) as SlNo, ID, videoid, title
FROM TableName) T
WHERE SlNo>=10
ORDER BY id_field
I dont't think there's LIMIT in SQL server. Use TOP instead. TOP returns the first N rows of a query, so if it's TOP 10, even if you have a thousand rows, it will only return the first 10. Try this...
SELECT TOP 60 *
FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
You can use following method for this purpose:
Method 1: ORDER BY
SELECT *
FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
ORDER BY ID OFFSET 21 ROWS FETCH NEXT 20 ROWS ONLY
Method 2: ROW_NUMBER
SELECT *
FROM ( SELECT *,
ROW_NUMBER()OVER (ORDER BY ID)row
FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
)z
WHERE row>20
AND row<=40
Method 3: Top N
SELECT TOP 20 *
FROM ( SELECT TOP 40 *
FROM [movie].[dbo].[movies]
WHERE title like '%' + '%s' + '%'
ORDER BY ID
)z
ORDER BY ID DESC
I am working on online question application.
I am Fetching Records from a database.
I have SQL database holding 1000 question in 10 set. I mean each set containing 100 questions. How can I take 20 random questions from each set? I mean how can I select 2 (as per request) random question from each set?
Try:
SELECT TOP 20 * FROM [YourTable] ORDER By NEWID()
More About NEWID().
If you need to get 20 random questions from each group here is an SQLFiddle example. SetNum here is a set ID
select * from
(
select t.*,
ROW_NUMBER()
over (partition by setNum order by NewId()) rNum from t
) t2 where rNum<=20
Try this if you want 2 random questions from each SET...
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 1) ORDER By NEWID()
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 2) ORDER By NEWID()
UNION
.
.
.
.
UNION
SELECT TOP 2 * FROM (SELECT * FROM [YourTable] WHERE SET_ID = 10) ORDER By NEWID()