hie all,
my query is this
select * from [order] where createdon<getdate()-7
and orderid between
(select top 1 orderid from [order] where createdon<getdate()-7 order by orderid) as oId
and oId+100 order by orderid
It is giving error. please tell me where is it going wrong
my intention is to get 100 orders from order table which are older than 7 days. and please dont suggest fetching it using row_number
Thanks
You can't alias expressions in the WHERE clause. But since your subquery returns just one row, you could cross join it to the [order] table and filter on the returned top orderid value like this:
SELECT [order].*
FROM [order]
CROSS JOIN (
SELECT TOP 1 orderid
FROM [order]
WHERE createdon < GETDATE() - 7
ORDER BY orderid
) toporder
WHERE [order].createdon < GETDATE() - 7
AND [order].orderid BETWEEN toporder.orderid AND toporder.orderid + 100
select * from
(
select top 100 * from [order] where
createdon<dateadd(day, -7, getdate())
order by orderid desc
)
order by orderid asc
Assume you use MSSQL, use TOP keyword to limit output :
SELECT TOP 100 ...
Related
There is a table which contains 50 records. I want to select first 10 records without using TOP keyword.
In SQL Server 2012+ you can use OFFSET ... FETCH
SELECT *
FROM YourTable
ORDER BY YourColumn ASC
OFFSET 0 ROWS
FETCH FIRST 10 ROWS ONLY
You can use ROW_NUMBER and Common Table Expression to query any range of data.
USE AdventureWorks2012;
GO
WITH OrderedOrders AS
(
SELECT SalesOrderID, OrderDate,
ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
FROM Sales.SalesOrderHeader
)
SELECT SalesOrderID, OrderDate, RowNumber
FROM OrderedOrders
WHERE RowNumber <= 10 -- other conditions: RowNumber between 50 and 60
Refere ROW NUMBER Here
Although it's probably the same thing internally, you can use
set rowcount 10
and then run the query.
I guess you can try something like this:
SELECT t.Id, t.Name FROM Table t
WHERE 10 > (SELECT count(*) FROM Table t2 WHERE t.id > t2.id)
You can use ROW_NUMBER. Let's say your table contains columns ID and Name. In that case you can use such query:
SELECT t.Id, t.Name
FROM (
SELECT ID, Name,
ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber
FROM TableName
) t
WHERE RowNumber <= 10
does anyone know how can I subtract top two rows from one column only using one id? Here's my sample query:
SELECT top 2 a.consumption,
coalesce(a.consumption -
(SELECT b.consumption
FROM tbl_t_billing b
WHERE b.id = a.id + 1), a.consumption) AS diff
FROM tbl_t_billing a
WHERE a.customerId = '5'
ORDER BY a.dateCreated DESC
I want to know how to get the difference between the top 2 rows using one id from the consumption column using the customerId #5. I've tried but I can't get the right query for that. Can somebody help me please? Thanks!
try this:
;with cte as
(
select consumption, customerId,
row_number() over (partiton by customerid order by datecreated desc) rn
from tbl_t_billing where customerId = '5'
)
select a.customerId, a.consumption,
coalesce((a.consumption - b.consumption), a.consumption) consumption_diff
from cte a left outer join cte b on a.rn + 1 = b.rn
where a.rn = 1
declare #tbl_t_billing table(consumption int, customerId int, datecreated datetime)
insert into #tbl_t_billing
values
(10,5,'20100101'),
(7,5,'20000101'),
(9,4,'20100101'),
(5,4,'20000101'),
(8,3,'20100101'),
(3,3,'20000101'),
(7,2,'20100101'),
(3,2,'20000101'),
(4,1,'20100101'),
(2,1,'20000101')
-- get the difference between the last two consumption values for each customerId
select
customerId,
sum(consumption) diff
from(
select
customerId,
consumption *
case row_number() over(partition by customerId order by datecreated desc)
when 1 then 1 when 2 then -1
end consumption
from #tbl_t_billing
) t
group by customerId
I have a SQL Server table. This table has two tables: Order and OrderInProgress. These two tables have similar structures:
Order[InProgress]
-----------------
ID (uniqueidentifier)
CreateDate
...
I need to get the latest Order or OrderInProgress
DECLARE #latestOrderID uniqueidentifier
#latestOrderID = ?
How do I set #latestOrderID to the most recent Order or OrderInProgress ID? I can't figure out how to do this in SQL.
Thank you!
Try this, which should be more efficient whenever it matters.
select top 1 ID from (
select top 1 ID from Order order by ID desc
union all
select top 1 ID from OrderInProgress order by ID desc
) T
order by ID desc
Have you tried:
SELECT TOP 1 #latestOrderID = ID FROM [Order] ORDER BY CreateDate DESC
SELECT * FROM
(SELECT 'Order' tablename, max(ID) max_id FROM Order
UNION
SELECT 'OrderInProgress' tablename, max(ID) max_id FROM OrderInProgress
) maxes ORDER BY max_id DESC
I want to select records from 1000 to 2000 rows and so on in batch of 1000.
I have written query to select top 1000 records but how can i select from 1000 to 2000.
can you help me with a query that can select those records.
SELECT TOP 1000 *
FROM tblProductInformation p1 INNER JOIN tblProduct1 p
ON p.productname = p1.productname
I think you need to order on specific a column, for example order on the primary key.
SELECT *
FROM
(
SELECT tbl.*, p.*, ROW_NUMBER() OVER (ORDER BY ProductID_PRIMARYKEY) rownum
FROM tblProductInformation as tbl INNER JOIN tblProduct1 p
ON p.productname = p1.productname
) seq
WHERE seq.rownum BETWEEN 1000 AND 2000
WITH cte AS(
SELECT ROW_NUMBER()OVER(Order By p1.productname ASC, p1.ID ASC) As RowNum
,p1 .*
from tblProductInformation p1
inner join tblProduct1 p on p.productname = p1.productname
)
SELECT * FROM cte
WHERE RowNum BETWEEN #FromRowNum AND #ToRowNum
ROW_NUMBER: http://msdn.microsoft.com/en-us/library/ms186734.aspx
Paging on SQL-Server: http://www.mssqltips.com/sqlservertip/1175/page-through-sql-server-results-with-the-rownumber-function/
WITH Results AS (
select TOP 1000 f.*, ROW_NUMBER() OVER (ORDER BY f.[type]) as RowNumber
from tblProductInformation f
) select *
from Results
where RowNumber between 1001 and 2000
tutorial
Answer Late .. but could be helpful for some one coming here ... simple one
Another simple approach ...
You can create a similar table "tblProductInformation_tmp" OR #tblProductInformation_tmp - with an extra column "UniqueID" and make that auto-increment IDENTITY column.
then just insert the same data to table :
insert * into tblProductInformation_tmp
select * from tblProductInformation
Now its simple ryt :
select * from tblProductInformation_tmp where UniqueID < 1001
select * from tblProductInformation_tmp where UniqueID between 1001 and 2001
:) Dont forget to delete : tblProductInformation_tmp
Rigin
I have two columns:
namecode name
050125 chris
050125 tof
050125 tof
050130 chris
050131 tof
I want to group by namecode, and return only the name with the most number of occurrences. In this instance, the result would be
050125 tof
050130 chris
050131 tof
This is with SQL Server 2000
I usually use ROW_NUMBER() to achieve this. Not sure how it performs against various data sets, but we haven't had any performance issues as a result of using ROW_NUMBER.
The PARTITION BY clause specifies which value to "group" the row numbers by, and the ORDER BY clause specifies how the records within each "group" should be sorted. So partition the data set by NameCode, and get all records with a Row Number of 1 (that is, the first record in each partition, ordered by the ORDER BY clause).
SELECT
i.NameCode,
i.Name
FROM
(
SELECT
RowNumber = ROW_NUMBER() OVER (PARTITION BY t.NameCode ORDER BY t.Name),
t.NameCode,
t.Name
FROM
MyTable t
) i
WHERE
i.RowNumber = 1;
select distinct namecode
, (
select top 1 name from
(
select namecode, name, count(*)
from myTable i
where i.namecode = o.namecode
group by namecode, name
order by count(*) desc
) x
) as name
from myTable o
SELECT max_table.namecode, count_table2.name
FROM
(SELECT namecode, MAX(count_name) AS max_count
FROM
(SELECT namecode, name, COUNT(name) AS count_name
FROM mytable
GROUP BY namecode, name) AS count_table1
GROUP BY namecode) AS max_table
INNER JOIN
(SELECT namecode, COUNT(name) AS count_name, name
FROM mytable
GROUP BY namecode, name) count_table2
ON max_table.namecode = count_table2.namecode AND
count_table2.count_name = max_table.max_count
I did not try but this should work,
select top 1 t2.* from (
select namecode, count(*) count from temp
group by namecode) t1 join temp t2 on t1.namecode = t2.namecode
order by t1.count desc
Here are to examples that you could use but the temp table use is more efficient than the view, but was done on a small data sample. You would want to check your own statistics.
--Creating A View
GO
CREATE VIEW StateStoreSales AS
SELECT t.state,t.stor_id,t.stor_name,SUM(s.qty) 'TotalSales'
,ROW_NUMBER() OVER (PARTITION BY t.state ORDER BY SUM(s.qty) DESC) AS 'Rank'
FROM [dbo].[sales] s
JOIN [dbo].[stores] t ON (s.stor_id = t.stor_id)
GROUP BY t.state,t.stor_id,t.stor_name
GO
SELECT * FROM StateStoreSales
WHERE Rank <= 1
ORDER BY TotalSales Desc
DROP VIEW StateStoreSales
---Using a Temp Table
SELECT t.state,t.stor_id,t.stor_name,SUM(s.qty) 'TotalSales'
,ROW_NUMBER() OVER (PARTITION BY t.state ORDER BY SUM(s.qty) DESC) AS 'Rank' INTO #TEMP
FROM [dbo].[sales] s
JOIN [dbo].[stores] t ON (s.stor_id = t.stor_id)
GROUP BY t.state,t.stor_id,t.stor_name
SELECT * FROM #TEMP
WHERE Rank <= 1
ORDER BY TotalSales Desc
DROP TABLE #TEMP