ApplySimple Formula for last year in Microstrategy Netezza syntax - netezza

I'd like some help to convert the following applysimple statement to it's netezza equivalent.
ApplySimple("(
select top 1 tradyrcode
from tradingyear
where tradyrcode < (
select max(tradyrcode)
from yrdays yd, control c
where c.systemdate = yd.datecode
)
order by 1 desc
)",0)
I think I need to change the top 1 to limit 1 for it to work in netezza.
Any help would be much appreciated!

Where ‘top nn’ is at the beginning of the statement, ‘limit nn’ has to be at the very end, after a possible ‘order by’:
select tradyrcode
from trading-year
where tradyrcode < (
select max(tradyrcode)
from yrdays yd, control c
where c.systemdate = yd.datecode
)
order by 1 desc
limit 1

Related

How to filter on set of ID values without using subquery

I was wondering if someone can help me, I need to show this in oracle.
For that I use this select:
SELECT m.idMedicamento, m.nombre, m.precio
FROM medicamento m
WHERE m.idMedicamento IN (
SELECT idMedicamento
FROM (
SELECT idMedicamento
FROM medicamento
ORDER BY precio ASC)
WHERE ROWNUM <=3
)
OR m.idMedicamento IN (
SELECT idMedicamento
FROM (
SELECT idMedicamento
FROM medicamento
ORDER BY precio DESC)
WHERE ROWNUM <=3
)
ORDER BY m.precio DESC;
but the problem is that I can't use subselects I need to use functions or procedures, and I thought in this function:
CREATE OR REPLACE FUNCTION MAXI RETURN FLOAT IS
total INT := 0;
CURSOR ANIO IS
SELECT idMedicamento
FROM medicamento
ORDER BY precio DESC;
a anio%ROWTYPE;
BEGIN
OPEN ANIO;
LOOP
FETCH ANIO INTO a;
EXIT WHEN ANIO%NOTFOUND;
END LOOP;
CLOSE ANIO;
RETURN ROUND(a ,2);
END;
This is a function just for return the maximum, but I can't return the cursor. I dont know if you can understand me, thanks for your time.
No, you cannot return a cursor and use that in a SQL statement WHERE clause the way you seem to want to do.
You could write a function to return the id values you are looking for as a TABLE OF NUMBER but you would still need to use a subquery to access its results in your main query. I.e.,
WHERE idMedicament IN ( SELECT * FROM TABLE(my_custom_function()) )
So, I think a function to returns the values of idMedicamento that you want to filter on is not going to work well with your "no subqueries" limitation.
Alternate approach #1
Incidentally, on Oracle 12c, you can write your query with no subqueries and no functions like this:
SELECT m.idMedicamento, m.nombre, m.precio,
case when rownum() over ( order by idMedicamento asc ) <= 3
or rownum() over ( order by idMedicamento desc ) <= 3 THEN 'Y' ELSE null END include_flag
FROM medicamento m
ORDER BY include_flag nulls last, m.precio DESC
FETCH FIRST 6 ROWS ONLY;
Alternate approach #2
I assume you cannot use subqueries because you are using a tool or a framework that is building your SQL for you. If that is the case, perhaps you cannot use windowing functions (i.e., rownum() over (...)) either. You can get around this by making a view and then writing your query against the view.
Like this:
CREATE OR REPLACE VIEW medicamento_v AS
SELECT m.idMedicamento, m.nombre, m.precio,
rownum() over ( order by idMedicamento asc) asc_order,
rownum() over ( order by idMedicamento desc) desc_order
FROM medicamento m;
SELECT m.idMedicamento, m.nombre, m.precio
FROM medicameno_v m
WHERE ( asc_order <= 3 OR desc_order <= 3 )
ORDER BY m.precio DESC;

Limiting results in SQL Server Compact

From a table do I want to select the first 4 rows after the first one. I had this in MySQL working as the following:
SELECT * FROM `yp_playlist` LIMIT 1, 4;
I have done some research to see the SQL Server version of this query and came out on the following but this keeps resulting me into an error which keeps me clueless for now.
SELECT id, entry
FROM (
SELECT id, entry, ROW_NUMBER() OVER (ORDER BY id) AS RowNum
FROM playlist
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN 0 AND 10
This is the error:
There was an error parsing the query. [ Token line number = 3, Token line offset = 36, Token in error = OVER ]
With SQL Server Compact 4.0 you can use;
SELECT * FROM [Orders] ORDER BY [Order Date] OFFSET 1 ROWS
FETCH NEXT 4 ROWS ONLY;
SELECT TOP 10 *
FROM ( SELECT id, entry
FROM playlist
ORDER BY id )
one way is to set rowcount
e.g
set rowcount 4
then order your data so you get the ones you want at the top

Get the missing value in a sequence of numbers

I made the following query for the SQL Server backend
SELECT TOP(1) (v.rownum + 99)
FROM
(
SELECT incrementNo-99 as id, ROW_NUMBER() OVER (ORDER BY incrementNo) as rownum
FROM proposals
WHERE [year] = '12'
) as v
WHERE v.rownum <> v.id
ORDER BY v.rownum
to find the first unused proposal number.
(It's not about the lastrecord +1)
But I realized ROW_NUMBER is not supported in access.
I looked and I can't find something similar.
Does anyone know how to get the same result as a ROW_NUMBER in access?
Maybe there's a better way of doing this.
Actually people insert their proposal No (incrementID) with no constraint. This number looks like this 13-152. xx- is for the current year and the -xxx is the proposal number. The last 3 digits are supposed to be incremental but in some case maybe 10 times a year they have to skip some numbers. That's why I can't have the auto increment.
So I do this query so when they open the form, the default number is the first unused.
How it works:
Because the number starts at 100, I do -99 so it starts at 1.
Then I compare the row number with the id so it looks like this
ROW NUMBER | ID
1 1 (100)
2 2 (101)
3 3 (102)
4 5 (104)<--------- WRONG
5 6 (105)
So now I know that we skip 4. So I return (4 - 99) = 103
If there's a better way, I don't mind changing but I really like this query.
If there's really no other way and I can't simulate a row number in access, i will use the pass through query.
Thank you
From your question it appears that you are looking for a gap in a sequence of numbers, so:
SELECT b.akey, (
SELECT Top 1 akey
FROM table1 a
WHERE a.akey > b.akey) AS [next]
FROM table1 AS b
WHERE (
SELECT Top 1 akey
FROM table1 a
WHERE a.akey > b.akey) <> [b].[akey]+1
ORDER BY b.akey
Where table1 is the table and akey is the sequenced number.
SELECT T.Value, T.next -1 FROM (
SELECT b.Value , (
SELECT Top 1 Value
FROM tblSequence a
WHERE a.Value > b.Value) AS [next]
FROM tblSequence b
) T WHERE T.next <> T.Value +1

msg 102,level 15,state 1,line 9 Incorrect syntax near '('-

I am working on a cross tab query in SQL Server 2008. Everything appear fine apart from this error I am getting.
Here is my code:
select * from
(select ITEM_CODE,NET_PRODUCTION_QUANTITY,RAW_MATERIAL_CODE,DATE_ID from dbo.ODST_PRODUCTION_TRANS
) n
pivot
(sum(NET_PRODUCTION_QUANTITY) for datename(month,DATE_ID) In ([January],[February],[March],[April],[May],[June])) as pvt
where RAW_MATERIAL_CODE = 'X' and DATE_ID between '01-Jan-11' and '30-Jun-11'.
The problem is where the datename(month,date_id) but I can't figure it out. Can anyone give me a solution?
Thanks in advance
I don't think the FOR part of a pivot can be a calculated value at the time of pivot and it must be in your result set.
select * from
(select ITEM_CODE,NET_PRODUCTION_QUANTITY,RAW_MATERIAL_CODE,DATE_ID,datename(month,DATE_ID) as dn from dbo.ODST_PRODUCTION_TRANS
) n
pivot
(sum(NET_PRODUCTION_QUANTITY) for dn In ([January],[February],[March],[April],[May],[June])) as pvt
where RAW_MATERIAL_CODE = 'X' and DATE_ID between '01-Jan-11' and '30-Jun-11'
Try
select * from
(select ITEM_CODE,NET_PRODUCTION_QUANTITY,RAW_MATERIAL_CODE,DATE_ID, datename(month,DATE_ID) as Month from dbo.ODST_PRODUCTION_TRANS
) n
pivot
(
sum(NET_PRODUCTION_QUANTITY)
for Month
In ([January],[February],[March],[April],[May],[June])
) as pvt
where RAW_MATERIAL_CODE = 'X' and DATE_ID between '01-Jan-11' and '30-Jun-11'
I don't think the pivot likes the datename expression, so I've moved it into the query.
it should be like this:
select * from
(select ITEM_CODE,NET_PRODUCTION_QUANTITY,RAW_MATERIAL_CODE,DATE_ID,datename(month,[DATE_ID]) as dtt
from dbo.ODST_PRODUCTION_TRANS) as n
pivot
(
sum(NET_PRODUCTION_QUANTITY)
for [dtt] IN ([January],[February],[March],[April],[May],[June])) as pvt
where RAW_MATERIAL_CODE = 'X' and DATE_ID between '01-Jan-11' and '30-Jun-11'

How do I select last 5 rows in a table without sorting?

I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.
This is just about the most bizarre query I've ever written, but I'm pretty sure it gets the "last 5" rows from a table without ordering:
select *
from issues
where issueid not in (
select top (
(select count(*) from issues) - 5
) issueid
from issues
)
Note that this makes use of SQL Server 2005's ability to pass a value into the "top" clause - it doesn't work on SQL Server 2000.
Suppose you have an index on id, this will be lightning fast:
SELECT * FROM [MyTable] WHERE [id] > (SELECT MAX([id]) - 5 FROM [MyTable])
The way your question is phrased makes it sound like you think you have to physically resort the data in the table in order to get it back in the order you want. If so, this is not the case, the ORDER BY clause exists for this purpose. The physical order in which the records are stored remains unchanged when using ORDER BY. The records are sorted in memory (or in temporary disk space) before they are returned.
Note that the order that records get returned is not guaranteed without using an ORDER BY clause. So, while any of the the suggestions here may work, there is no reason to think they will continue to work, nor can you prove that they work in all cases with your current database. This is by design - I am assuming it is to give the database engine the freedom do as it will with the records in order to obtain best performance in the case where there is no explicit order specified.
Assuming you wanted the last 5 records sorted by the field Name in ascending order, you could do something like this, which should work in either SQL 2000 or 2005:
select Name
from (
select top 5 Name
from MyTable
order by Name desc
) a
order by Name asc
You need to count number of rows inside table ( say we have 12 rows )
then subtract 5 rows from them ( we are now in 7 )
select * where index_column > 7
select * from users
where user_id >
( (select COUNT(*) from users) - 5)
you can order them ASC or DESC
But when using this code
select TOP 5 from users order by user_id DESC
it will not be ordered easily.
select * from table limit 5 offset (select count(*) from table) - 5;
Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.
SELECT TOP 5 * FROM [TableName]
Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.
SELECT TOP 5 * FROM MyTable
ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
Search 5 records from last records you can use this,
SELECT *
FROM Table Name
WHERE ID <= IDENT_CURRENT('Table Name')
AND ID >= IDENT_CURRENT('Table Name') - 5
If you know how many rows there will be in total you can use the ROW_NUMBER() function.
Here's an examble from MSDN (http://msdn.microsoft.com/en-us/library/ms186734.aspx)
USE AdventureWorks;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS 'RowNumber'
FROM Sales.SalesOrderHeader
)
SELECT *
FROM OrderedOrders
WHERE RowNumber BETWEEN 50 AND 60;
In SQL Server 2012 you can do this :
Declare #Count1 int ;
Select #Count1 = Count(*)
FROM [Log] AS L
SELECT
*
FROM [Log] AS L
ORDER BY L.id
OFFSET #Count - 5 ROWS
FETCH NEXT 5 ROWS ONLY;
Try this, if you don't have a primary key or identical column:
select [Stu_Id],[Student_Name] ,[City] ,[Registered],
RowNum = row_number() OVER (ORDER BY (SELECT 0))
from student
ORDER BY RowNum desc
You can retrieve them from memory.
So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.
There is a handy trick that works in some databases for ordering in database order,
SELECT * FROM TableName ORDER BY true
Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.
select *
from table
order by empno(primary key) desc
fetch first 5 rows only
Last 5 rows retrieve in mysql
This query working perfectly
SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC
or
select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc
When number of rows in table is less than 5 the answers of Matt Hamilton and msuvajac is Incorrect.
Because a TOP N rowcount value may not be negative.
A great example can be found Here.
i am using this code:
select * from tweets where placeID = '$placeID' and id > (
(select count(*) from tweets where placeID = '$placeID')-2)
In SQL Server, it does not seem possible without using ordering in the query.
This is what I have used.
SELECT *
FROM
(
SELECT TOP 5 *
FROM [MyTable]
ORDER BY Id DESC /*Primary Key*/
) AS T
ORDER BY T.Id ASC; /*Primary Key*/
DECLARE #MYVAR NVARCHAR(100)
DECLARE #step int
SET #step = 0;
DECLARE MYTESTCURSOR CURSOR
DYNAMIC
FOR
SELECT col FROM [dbo].[table]
OPEN MYTESTCURSOR
FETCH LAST FROM MYTESTCURSOR INTO #MYVAR
print #MYVAR;
WHILE #step < 10
BEGIN
FETCH PRIOR FROM MYTESTCURSOR INTO #MYVAR
print #MYVAR;
SET #step = #step + 1;
END
CLOSE MYTESTCURSOR
DEALLOCATE MYTESTCURSOR
Thanks to #Apps Tawale , Based on his answer, here's a bit of another (my) version,
To select last 5 records without an identity column,
select top 5 *,
RowNum = row_number() OVER (ORDER BY (SELECT 0))
from [dbo].[ViewEmployeeMaster]
ORDER BY RowNum desc
Nevertheless, it has an order by, but on RowNum :)
Note(1): The above query will reverse the order of what we get when we run the main select query.
So to maintain the order, we can slightly go like:
select *, RowNum2 = row_number() OVER (ORDER BY (SELECT 0))
from (
select top 5 *, RowNum = row_number() OVER (ORDER BY (SELECT 0))
from [dbo].[ViewEmployeeMaster]
ORDER BY RowNum desc
) as t1
order by RowNum2 desc
Note(2): Without an identity column, the query takes a bit of time in case of large data
Get the count of that table
select count(*) from TABLE
select top count * from TABLE where 'primary key row' NOT IN (select top (count-5) 'primary key row' from TABLE)
If you do not want to arrange the table in ascending or descending order. Use this.
select * from table limit 5 offset (select count(*) from table) - 5;

Resources