Add ID column to a query result - sql

This is my first time asking a question about T-SQL and I am a beginner with it. I have a SQL query which consists of two CTE's filtered down to less than 10 rows. I am using a SUM statement to get a running total:
Sum(Diff) OVER(ORDER BY DateAdded) AS Summary
DateAdded has the same value for several rows. Therefore, it does not give me a running total for each row. I need to create a field that simply counts the number of rows (similar to a PK in a DB table) so I can use it for my ORDER BY clause. If my understanding is correct, this is what I need to do to make it work. How can I add an enumerated column to the query result set? Please note, I do not want to ALTER a table, just add a column to the query result. I hope what I wrote is clear. Thank you!

Instead of using count() or sum() you can use row_number() which will give a distinct row number, starting at 1, for each row in your result set:
SELECT ROW_NUMBER() OVER (ORDER BY dateAdded) as Summary

Try this:
DECLARE #Result TABLE
(
DT DATETIME
)
INSERT INTO #Result SELECT '1 Jan 1900'
INSERT INTO #Result SELECT '1 Jan 1900'
SELECT ROW_NUMBER() OVER(ORDER BY DT DESC) AS "Row Number", DT
FROM #Result

I believe that you can just add NEWID() to your ORDER BY:
SELECT SUM(diff) OVER (ORDER BY DateAdded, NEWID()) AS Summary

Related

new column with row number sql

I have data like below with two columns, I need an output with new column shown below
Input -
Name,Date,Value
Test1,20200901,55
Test1,20200901,100
Test1,20200901,150
Test1,20200805,25
Test1,20200805,30
Row number is based on data from column - Name and Date
Output,
Name,Date,Value, row_number
Test1,20200901,55,1
Test1,20200901,100,1
Test1,20200901,150,1
Test1,20200805,25,2
Test1,20200805,30,2
The query using Partition didn't help
select *, row_number() over (partition by Date) as Rank from Table
Can someone please help here
Thank you very much
You want dense_rank():
select *,
dense_rank() over (order by Date) as Rank
from Table;
There is something suspicious when you are using partition by without order by (even if the underlying database supports that).
Use dense_rank() - and an order by clause:
select t.*, dense_rank() over (order by Date) as rn from mytable t
This gives you a sequential number that starts at 1 on the earliest date value increments without gaps everytime date changes.

Insert data into temporary Table

I'm using SQL Server and I'm trying to build a temporary Table where it have a column retrieved by an currently exciting table and insert in each row a date.
For example I have
select NumberID into #Table0
from Table1
where numcue in [conditions]
In the new Table0 I have the NumberID ordered by a certain criteria. But in that exact same order I want to introduce a date for each row.
Is there any way to do it without using a CREATE TABLE, or INSERT ( I don't have permissions for that)
Thanks in advance
-------EDITION--- (MORE INFO)
Maybe I wasn't clear about it, long story short is that I have IDNUMBER in the TABLE1 on my Datawarehouse (10k+rows), but it have 20 dates for each IDNUMBER.
In an Excel I have the date I need to retrieve for each IDNUMBER, but I don't know how to retrieve that exact info directly with a QUERY. And the dates doesn't have a criteria is just random date for each IDNUMBER so I can't code it directly.
So what I was trying to do, is put each IDNUMBER with the date of the Excel in a temporary Table and then keep looking info with that
Hope this help to explain a little further
Thanks in advance and for all the current answers
So you mean something like this?
select NumberID, GETDATE() AS DateColumn into #Table0
from Table1
where numcue in [conditions]
I think you can do it by using a CTE (Common Table Expression) to find the row number for your ID's.
I'm not sure if this is the case, but I've understood you want to increment the date for each row, e.g.:
NumberID|Date
1 |2018-01-01
3 |2018-01-02
12 |2018-01-03
25 |2018-01-04
In that case, I've supplied some code that uses the sys_objects table as an example:
DECLARE #FirstDate DATE = '20180101'
;WITH CTE
AS
(
SELECT TOP (100) PERCENT object_id, ROW_NUMBER() OVER (ORDER BY object_id ASC) AS RowNumber
FROM master.sys.objects
ORDER BY object_id
)
SELECT object_id, DATEADD(dd, RowNumber-1, #FirstDate) AS Date, RowNumber
FROM CTE;
You can ignore the RowNumber column - I've just added for you to understand that it is a sequence.
For you case in particular, I think this code should work - remember to specify your initial date:
DECLARE #FirstDate DATE = '20180101'
;WITH CTE
AS
(
SELECT TOP (100) PERCENT NumberID, ROW_NUMBER() OVER (ORDER BY NumberID ASC) AS RowNumber
FROM Table1
WHERE numcue IN [conditions]
)
SELECT NumberID, DATEADD(dd, RowNumber-1, #FirstDate) AS Date
FROM CTE;

How to retrieve specific rows from SQL Server table?

I was wondering is there a way to retrieve, for example, 2nd and 5th row from SQL table that contains 100 rows?
I saw some solutions with WHERE clause but they all assume that the column on which WHERE clause is applied is linear, starting at 1.
Is there other way to query a SQL Server table for a specific rows in case table doesn't have a column whose values start at 1?
P.S. - I know for a solution with temporary tables, where you copy your select statement output and add a linear column to the table. I am using T-SQL
Try this,
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ColumnName ASC) AS rownumber
FROM TableName
) as temptablename
WHERE rownumber IN (2,5)
With SQL Server:
; WITH Base AS (
SELECT *, ROW_NUMBER() OVER (ORDER BY id) RN FROM YourTable
)
SELECT *
FROM Base WHERE RN IN (2, 5)
The id that you'll have to replace with your primary key or your ordering, YourTable that is your table.
It's a CTE (Common Table Expression) so it isn't a temporary table. It's something that will be expanded together with your query.
There is no 2nd or 5th row in the table.
There is only the 2nd or 5th result in a resultset that you return, as determined by the order you specify in that query.
If you are on SQL Server 2005 or above, you could use Row_Number() function. Ex:
;With CTE as (
select col1, ..., row_number() over (order by yourOrderingCol) rn
from yourTable
)
select col1,...
from cte
where rn in (2,5)
Please note that yourOrderingCol will decide the value of row number (i.e. rn).

SQL "over" partition WHERE date between two values

I have a query that partitions and ranks "Note" records, grouping them by ID_Task (users add notes for each task). I want to rank the notes by date, but I also want to restrict it so they're ranked between two dates.
I'm using SQL Server 2008. So far my SELECT looks like this:
SELECT Note.ID,
Note.ID_Task,
Note.[Days],
Note.[Date],
ROW_NUMBER() OVER (PARTITION BY ID_Task ORDER BY CAST([Date] AS DATE), Edited ASC) AS Rank
FROM
Note
WHERE
Note.Locked = 1 AND Note.Deleted = 0
Now, I assume that if I put the WHERE clause at the bottom, although they'll still have ranks, I might or might not get item with rank 1, as it might get filtered out. So is there a way I can only partition records WHERE , ignoring all of the others? I could partition a sub-query I guess.
The intention is to use the rank number to find the most recent note for each task, in another query. So in that query I'll join with this result WHERE rank = 1.
row_number() operates after where. You'll always get a row 1.
For example:
declare #t table (id int)
insert #t values (3), (1), (4)
select row_number() over (order by id)
from #t
where id > 1
This prints:
1
2

use Row_number after applying distinct

I am creating an SP which gives some result by applying distinct on it, now I want to implement sever side paging, so I tried using Row_number on distinct result like:
WITH CTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY tblA.TeamName DESC)
as Row,tblA.TeamId,tblA.TeamName,tblA.CompId,tblA.CompName,tblA.Title,tblA.Thumbnail,tblA.Rank,tblA.CountryId,tblA.CountryName
FROM
(
--The table query starts with SELECT
)tblA
)
SELECT CTE.* FROM CTE
WHERE CTE.Row BETWEEN #StartRowIndex AND #StartRowIndex+#NumRows-1
ORDER BY CTE.CountryName
but rows are first assigned RowNumber then distinct get applied that is why I am getting duplicate values, how to get distinct rows first then get row numbers for the same.
Any solution on this? Am I missing something?
need answer ASAP.
thanks in advance!
Don't you need to add "partition by" to your ROW_NUMBER statement?
ROW_NUMBER() OVER(Partition by ___, ___, ORDER BY tblA.TeamName DESC)
In the blank spaces, place the column names you would like to create a new row number for. Duplicates will receive a number that is NOT 1 so you might not need the distinct.
To gather the unique values you could write a subquery where the stored procedure only grabs the rows with a 1 in them.
select * from
(
your code
) where row = 1
Hope that helps.
I'm not sure why you're doing this:
WHERE CTE.Row BETWEEN #StartRowIndex AND #StartRowIndex+#NumRows-1