Get sequential rows that have same column values is SQL Server 2008 - sql-server-2008

I need to know the sequential rows which have some same values
I need the rows which have prsstatus value of 0 and then next row is 1

Another method, change MyTable to whatever your table is and change the ORDER BY clause to whatever columns you want to sort by.
;WITH MyTableSort AS (
SELECT TblID, EmpID, PrsDay, PrsTime, PrsStatus, ROW_NUMBER() OVER (ORDER BY MyTable.TblID) [Row] FROM MyTable
)
SELECT * FROM MyTableSort AS MyTableSortA
WHERE (MyTableSortA.PrsStatus = 0 AND EXISTS (SELECT 1 FROM MyTableSort WHERE MyTableSort.[Row] = MyTableSortA.[row]+1 AND MyTableSort.PrsStatus = 1))

Assuming you mean "next" row in terms of dense values on TblID:
select YTN.*
from YourTableName as YTN inner join
YourTableName as NR on NR.TblID = YTN.TblId + 1 and
NR.PrsStatus = 1 and YTN.PrsStatus = 0

Related

How to fix Number Of Row Per Page in SSRS Report?

I Have Fix 10 Rows Per Page , If 2records Comes From Query Then I Want To Show 8 Blank Rows. How To Fix It ?
This is a fairly generic example. It just counts the actual rows, calculates how many rows are required to round up to the nearest 10 and then UNIONs a query that generates blank rows.
SELECT *
FROM (
SELECT
RowN = ROW_NUMBER() OVER(ORDER BY myColumn), -- order by any column
*
FROM myTable
UNION ALL
SELECT
TOP (SELECT ExtraRows = (FLOOR((Count(*)+9)/10) * 10) - COUNT(*) FROM myTable) -- 10 here is rows per page
NewRowNumber = ROW_NUMBER() OVER (ORDER BY [object_id]) + (SELECT COUNT(*) FROM myTable)
,NULL, NULL, NULL -- one nulll value for each column in myTable
FROM sys.all_columns
) u
ORDER by u.RowN -- add any additional required sorting here
If your current query is not simple then dump the results of that into a temp table
SELECT *
INTO #t
FROM ...
myBigQuery
then change the references to myTable in the main query above to #t or whatever the temp table is called.
EDIT for using with SP
If using a Stored proc then you can dump the results of that into a temp table and do the same. For exmaple
CREATE TABLE #t (ColA int, ColB varchar(100)....)
INSERT INTO #t
EXEC myStoredProc
...
the main query from above
...
Just swap out all references to myTable with #t

run a query if a value on the last row is correct

Id like to run a query only if a value in the last row is correct. In my exemple if the value in ColumnA is 1 on the last row then i want to run MyQuery. But if the value is not 1 stop there and do nothing.
i've try with case and count(*) and also with If exists. but i keep getting error
SELECT CASE WHEN ((SELECT COUNT(*) FROM
(Select a.* from table as a order by a.index desc limit 1) as b
where b.ColumnA = 1)) > 0 )
THEN (MyQuery)
END
i've also try with if exists but it doesn'work either
if exists Select b.* from (Select a.* from table as a order by a.index desc limit 1) where b.ColumnA = 1
begin
(MyQuery)
end
can you point me what wrong in those query or maybee there's a better way to achive this.
EDIT. This query will be run on a trigger after each insert in that table the goal is to avoid running MyQuery on row that dont required it. MyQuery is a bit slow and most row dont required it to run.
I think we can rephrase your logic here to make it work as you want:
WITH cte AS (
SELECT ColumnA, ROW_NUMBER() OVER (ORDER BY index DESC) rn
FROM yourTable
)
(your query here)
WHERE (SELECT ColumnA FROM cte WHERE rn = 1) = 1;
The WHERE clause above would return either true or false, and would apply to all records in the potential result set from your query. That is, if the ColumnA value from the "last" record were 1, then you would get back the entire result set, otherwise it would be empty set.
Assuming your version of MariaDB supports neither ROW_NUMBER nor CTEs, then use:
(your query here)
WHERE (SELECT ColumnA FROM yourTable ORDER BY index DESC LIMIT 1) = 1;
It depends on what your query is.
INSERT ...
SELECT ... WHERE ... -- this could lead to zero rows being inserted
DELETE ...
WHERE NOT EXISTS ( SELECT ... ) -- this could lead to zero rows being deleted
UPDATE t1 JOIN t2 ... -- the JOIN may cause no rows to be updated
Note:
(Select a.* from table as a order by a.index desc limit 1) as b
where b.ColumnA = 1)) > 0 )
can be simplified (and sped up) to
( ( SELECT ColumnA FROM table ORDER BY index DESC LIMIT 1 ) = 1 )
Note that that is a true/false "expression", so it can be used in various places.

Query to fetch second highest salary from table [duplicate]

What is the simplest SQL query to find the second largest integer value in a specific column?
There are maybe duplicate values in the column.
SELECT MAX( col )
FROM table
WHERE col < ( SELECT MAX( col )
FROM table )
SELECT MAX(col)
FROM table
WHERE col NOT IN ( SELECT MAX(col)
FROM table
);
In T-Sql there are two ways:
--filter out the max
select max( col )
from [table]
where col < (
select max( col )
from [table] )
--sort top two then bottom one
select top 1 col
from (
select top 2 col
from [table]
order by col) topTwo
order by col desc
In Microsoft SQL the first way is twice as fast as the second, even if the column in question is clustered.
This is because the sort operation is relatively slow compared to the table or index scan that the max aggregation uses.
Alternatively, in Microsoft SQL 2005 and above you can use the ROW_NUMBER() function:
select col
from (
select ROW_NUMBER() over (order by col asc) as 'rowNum', col
from [table] ) withRowNum
where rowNum = 2
I see both some SQL Server specific and some MySQL specific solutions here, so you might want to clarify which database you need. Though if I had to guess I'd say SQL Server since this is trivial in MySQL.
I also see some solutions that won't work because they fail to take into account the possibility for duplicates, so be careful which ones you accept. Finally, I see a few that will work but that will make two complete scans of the table. You want to make sure the 2nd scan is only looking at 2 values.
SQL Server (pre-2012):
SELECT MIN([column]) AS [column]
FROM (
SELECT TOP 2 [column]
FROM [Table]
GROUP BY [column]
ORDER BY [column] DESC
) a
MySQL:
SELECT `column`
FROM `table`
GROUP BY `column`
ORDER BY `column` DESC
LIMIT 1,1
Update:
SQL Server 2012 now supports a much cleaner (and standard) OFFSET/FETCH syntax:
SELECT [column]
FROM [Table]
GROUP BY [column]
ORDER BY [column] DESC
OFFSET 1 ROWS
FETCH NEXT 1 ROWS ONLY;
I suppose you can do something like:
SELECT *
FROM Table
ORDER BY NumericalColumn DESC
LIMIT 1 OFFSET 1
or
SELECT *
FROM Table ORDER BY NumericalColumn DESC
LIMIT (1, 1)
depending on your database server. Hint: SQL Server doesn't do LIMIT.
The easiest would be to get the second value from this result set in the application:
SELECT DISTINCT value
FROM Table
ORDER BY value DESC
LIMIT 2
But if you must select the second value using SQL, how about:
SELECT MIN(value)
FROM ( SELECT DISTINCT value
FROM Table
ORDER BY value DESC
LIMIT 2
) AS t
you can find the second largest value of column by using the following query
SELECT *
FROM TableName a
WHERE
2 = (SELECT count(DISTINCT(b.ColumnName))
FROM TableName b WHERE
a.ColumnName <= b.ColumnName);
you can find more details on the following link
http://www.abhishekbpatel.com/2012/12/how-to-get-nth-maximum-and-minimun.html
MSSQL
SELECT *
FROM [Users]
order by UserId desc OFFSET 1 ROW
FETCH NEXT 1 ROW ONLY;
MySQL
SELECT *
FROM Users
order by UserId desc LIMIT 1 OFFSET 1
No need of sub queries ... just skip one row and select second rows after order by descending
A very simple query to find the second largest value
SELECT `Column`
FROM `Table`
ORDER BY `Column` DESC
LIMIT 1,1;
SELECT MAX(Salary)
FROM Employee
WHERE Salary NOT IN ( SELECT MAX(Salary)
FROM Employee
)
This query will return the maximum salary, from the result - which not contains maximum salary from overall table.
Old question I know, but this gave me a better exec plan:
SELECT TOP 1 LEAD(MAX (column)) OVER (ORDER BY column desc)
FROM TABLE
GROUP BY column
This is very simple code, you can try this :-
ex :
Table name = test
salary
1000
1500
1450
7500
MSSQL Code to get 2nd largest value
select salary from test order by salary desc offset 1 rows fetch next 1 rows only;
here 'offset 1 rows' means 2nd row of table and 'fetch next 1 rows only' is for show only that 1 row. if you dont use 'fetch next 1 rows only' then it shows all the rows from the second row.
Simplest of all
select sal
from salary
order by sal desc
limit 1 offset 1
select * from (select ROW_NUMBER() over (Order by Col_x desc) as Row, Col_1
from table_1)as table_new tn inner join table_1 t1
on tn.col_1 = t1.col_1
where row = 2
Hope this help to get the value for any row.....
Use this query.
SELECT MAX( colname )
FROM Tablename
where colname < (
SELECT MAX( colname )
FROM Tablename)
select min(sal) from emp where sal in
(select TOP 2 (sal) from emp order by sal desc)
Note
sal is col name
emp is table name
select col_name
from (
select dense_rank() over (order by col_name desc) as 'rank', col_name
from table_name ) withrank
where rank = 2
SELECT
*
FROM
table
WHERE
column < (SELECT max(columnq) FROM table)
ORDER BY
column DESC LIMIT 1
It is the most esiest way:
SELECT
Column name
FROM
Table name
ORDER BY
Column name DESC
LIMIT 1,1
As you mentioned duplicate values . In such case you may use DISTINCT and GROUP BY to find out second highest value
Here is a table
salary
:
GROUP BY
SELECT amount FROM salary
GROUP by amount
ORDER BY amount DESC
LIMIT 1 , 1
DISTINCT
SELECT DISTINCT amount
FROM salary
ORDER BY amount DESC
LIMIT 1 , 1
First portion of LIMIT = starting index
Second portion of LIMIT = how many value
Tom, believe this will fail when there is more than one value returned in select max([COLUMN_NAME]) from [TABLE_NAME] section. i.e. where there are more than 2 values in the data set.
Slight modification to your query will work -
select max([COLUMN_NAME])
from [TABLE_NAME]
where [COLUMN_NAME] IN ( select max([COLUMN_NAME])
from [TABLE_NAME]
)
select max(COL_NAME)
from TABLE_NAME
where COL_NAME in ( select COL_NAME
from TABLE_NAME
where COL_NAME < ( select max(COL_NAME)
from TABLE_NAME
)
);
subquery returns all values other than the largest.
select the max value from the returned list.
This is an another way to find the second largest value of a column.Consider the table 'Student' and column 'Age'.Then the query is,
select top 1 Age
from Student
where Age in ( select distinct top 2 Age
from Student order by Age desc
) order by Age asc
select age
from student
group by id having age< ( select max(age)
from student
)
order by age
limit 1
SELECT MAX(sal)
FROM emp
WHERE sal NOT IN ( SELECT top 3 sal
FROM emp order by sal desc
)
this will return the third highest sal of emp table
select max(column_name)
from table_name
where column_name not in ( select max(column_name)
from table_name
);
not in is a condition that exclude the highest value of column_name.
Reference : programmer interview
Something like this? I haven't tested it, though:
select top 1 x
from (
select top 2 distinct x
from y
order by x desc
) z
order by x
See How to select the nth row in a SQL database table?.
Sybase SQL Anywhere supports:
SELECT TOP 1 START AT 2 value from table ORDER BY value
Using a correlated query:
Select * from x x1 where 1 = (select count(*) from x where x1.a < a)
select * from emp e where 3>=(select count(distinct salary)
from emp where s.salary<=salary)
This query selects the maximum three salaries. If two emp get the same salary this does not affect the query.

MYSQL: Return results ONLY for the first true encountered SELECT expression

Desired result:
Return results ONLY for the first true encountered SELECT expression.
Explanation:
So, I have three different SELECT expresions:
SELECT * FROM table WHERE column1 = 'sometext' AND column2='1'
SELECT * FROM table WHERE column1 = 'someothertext' AND column2='2'
SELECT * FROM table WHERE column1 = 'somethirdtext' AND column2='3'
I want to have the results from 1. If 1. is returning NULL, I would like result from select number 2. If Select number 2. is returning NULL, I would like to use select number 3. and so on.
Please note that I am expecting more than one row to be returned for each condition that is true - and I only want the result from either SELECT 1) 2) or 3) (in that order)
It is important to only return results from the one single SELECT expression, so even if 2. and 3. would return something, I would only like results from 1.
The code I have right now is following that expected logic BUT when a I have more than one rows being returned by some of the below SELECTS, it gives me error:
1242 - Subquery returns more than 1 row
The code right now:
SELECT IFNULL( (SELECT * FROM table WHERE column = 'sometext'), IFNULL( (SELECT * FROM table WHERE column = 'someothertext'), IFNULL( (SELECT * FROM table WHERE column = 'somethirdtext'), 0 ) ) )
You're looking for COALESCE function.
SELECT COALESCE(
(SELECT col FROM t WHERE `column` = 'sometext'),
(SELECT col FROM t WHERE `column` = 'someothertext'),
(SELECT col FROM t WHERE `column` = 'somethirdtext')
);
-please, note that subquery should not return more than 1 row/column.
I would approach this slightly differently, since you can only return one row per condition anyway, I would use the following to limit the number of selects done:
SELECT *
FROM table
WHERE column IN ('sometext', 'someothertext', 'somethirdtext')
ORDER BY CASE column
WHEN 'sometext' THEN 1
WHEN 'someothertext' THEN 2
WHEN 'somethirdtext' THEN 3
END
LIMIT 1;
As pointed out in the comments, you can use FIELD for the sort too:
SELECT *
FROM table
WHERE column IN ('sometext', 'someothertext', 'somethirdtext')
ORDER BY FIELD(column, 'sometext', 'someothertext', 'somethirdtext')
LIMIT 1;
I think you can get multiple rows per condition using the following:
SELECT T.*
FROM Table T
INNER JOIN
( SELECT Column
FROM Table
WHERE column IN ('sometext', 'someothertext', 'somethirdtext')
ORDER BY FIELD(column, 'sometext', 'someothertext', 'somethirdtext')
LIMIT 1
) MinT
ON MinT.Column = T.Column;
Basically the subquery MinT does the same as before, ordering by whichever condition matches. Then gets the value for the column of the first match and limits the whole table to this value.
Example on SQL Fiddle
SELECT t.*
FROM
( SELECT o.column1, o.column2
FROM
( SELECT 1 AS ord, 'sometext' AS column1, '1' AS column2 UNION ALL
SELECT 2, 'someothertext', '2' UNION ALL
SELECT 3, 'somethirdtext', '3'
) AS o
WHERE EXISTS
( SELECT 1
FROM table AS td
WHERE td.column1 = o.column1
AND td.column2 = o.column2
)
ORDER BY o.ord
LIMIT 1
) AS d
JOIN
table AS t
ON t.column1 = d.column1
AND t.column2 = d.column2 ;
MySQL isn't my daily db so I might be off on this, but can't you just use LIMIT 1 on your subqueries?

renumber(set column to rank) a column after order by on that column

in sql, i want to do something like
update table set col = rank(col) order by col
how do i do this ?
Purpose :
currently the col has extreme values, like -14000, 23, 4000, 23000 ... they are used in asc, desc sort but when i plot them on a slider, having say 10 positions, each slider position has highly uneven data, so to even it out i wish to renumber the column,
-14000 becomes 0
23 becomes 1
4000 becomes 2
and so on
Used this :
update table set col = (select count(*) from (select col from table) as temptable where temptable.col <table.col );
In SQL Server, you can use two subqueries and the ROW_NUMBER function. In cases where you have duplicates in col, the ranking will follow standard competition ranking.
Sample script:
SELECT * INTO #TABLE
FROM
(
select -14000 col
union all SELECT 23
union all select 4000
union all SELECT 23 --sample duplicated data
) Unioned
UPDATE #TABLE
SET col =
(
SELECT top 1 rowNum
FROM
(
SELECT
col
, row_number() OVER (order by col) - 1 rowNum --starts at 0 rank
FROM #TABLE
) MySubQuery
WHERE MySubQuery.col = #TABLE.col
)