I want to get distinct dates from my dbtable named tblFormno2 in an ascending order.For that i've written the following query but its not working properly.
Column date_submit is declared as datetime
select distinct (convert(nvarchar(100),date_submit,103)) as dob from
tblFormno2 order by dob asc
Here the the output is shown as
05/07/2011
06/03/2011
06/07/2011
07/04/2011
08/01/2012
instead of
06/03/2011
07/04/2011
05/07/2011
06/07/2011
08/01/2012
How to solve this problem ???
How about
select convert(nvarchar(10), date_submit_inner, 103) as date_submit from
(
select distinct date_submit as date_submit_inner from tblFormno2
) as T
order by T.date_submit_inner asc
Your order by is not sorting by date_submit from the table. Is is sorting by the named output column of date_submit. If you specific the table name in the order by it should work. If that doesn't work, then try giving the output a different name than the table column.
select distinct (Convert(nvarchar(100),date_submit,103)) as date_submit
from tblFormno2
order by tblFormno2.date_submit asc
create table #temp
(
DT varchar(20)
)
Insert into #temp(DT)values('13/05/2011')
Insert into #temp(DT)values('03/06/2011')
Insert into #temp(DT)values('07/06/2011')
Insert into #temp(DT)values('04/07/2011')
Insert into #temp(DT)values('01/08/2011')
Select * from #temp
Below are the database records...
select (convert(varchar,Dt,107)) t into #t from #temp
select * from #t
drop table #temp
drop table #t
Related
I have a table of kicks between a number of football players. Most interactions have both a kicker and receiver, but sometimes the pass is made but never received. The table contains 3 columns. For purposes of the example, I have added a "PassID" column to assist with the description of the problem.
The table looks as follows:
create table #T (Player1 varchar(25),Action varchar(25),Player2 varchar(25),PassID int)
insert into #T select 'Jamie','Kicked to','Pierre',1
insert into #T select 'Pierre','Received from ','Jamie',1
insert into #T select 'Jamie','Kicked to ','Mohamed',2
insert into #T select 'Jamie','Received from ','Kun',3
insert into #T select 'Kun ','Kicked to','Jamie',3
insert into #T select 'Mohamed','Received from ','Pierre',4
insert into #T select 'Pierre','Kicked to','Mohamed',4
insert into #T select 'Mohamed','Kicked to','Kun',5
insert into #T select 'Jamie ','Kicked to ','Kun',6
insert into #T select 'Kun ','Received from ','Jamie',6
insert into #T select 'Jamie','Received from ','Kun',7
insert into #T select 'Kun ','Kicked to','Jamie',7
I have to answer the following question using SQL server:
How many unique interactions exist, where a unique interaction is defined as a kick between two players, whether completed or not and where the direction of the interaction does not matter?
In this simple example, I know the answer is 5,being:
Jamie/Pierre
Jamie/Mohamed
Jamie/Kun
Mohamed/Pierre
Mohamed/Kun
How do I extract this answer from the table using T-SQL statement?
SELECT COUNT(DISTINCT CASE
WHEN Player1 > Player2 THEN CONCAT(Player1,'+',Player2)
ELSE CONCAT(Player2,'+',Player1)
END )
FROM #T
WHERE Action = 'Kicked To';
Here is a SQL Fiddle
Try with the below code.
Select CONCAT(x.Player1,'/',x.Player2)Title from (
Select *,ROW_NUMBER() over (PARTITION by passid order by passid)Row from #T
)X
where Row=1
I want to delete from an existing table the entries that respond to a specific time range if they exist in this table, then calculate them and insert them to it.
If they do not exist create them and just insert to the table.
How is that possible to be done?
Could anyone give an example of this?
The table structure should be the following:
create table test_table
(
[Date] float
,[UserName] nvarchar(max)
,[SessionType] int
,[Duration] float
,[MessageCount] int
)
if you have a Column that Stores the DATE and TIME then you can just delete the records based on that.
Suppose I have a Column Called CreateDate on My table. Then I can Delete all records Created between 10.00 am and 11.00 Today by Just Giving
DELETE FROM MyTable WHERE
CreateDate BETWEEN '2018-01-12 10:00:00.000' AND '2018-01-12 11:00:00.000'
Now Insert the values again using the Normal INSERT statement
You can do in steps like this
First store the set of records in time range in a temp table
SELECT * INTO tempTable FROM YourTable WHERE CONVERT(FLOAT, [Date]) BETWEEN 43100.3603763503 AND 43110.3603763503
Then delete the records from the table
DELETE FROM YourTable WHERE CONVERT(FLOAT, [Date]) BETWEEN 43100.3603763503 AND 43110.3603763503
Then do the calculations as per your requirement with the data available in tempTable and insert the data into your table
INSERT INTO YourTable
SELECT * FROM tempTable
Then drop the tempTable
DROP TABLE tempTable
I am updating my solution to this thank you all for help.
create mytable table
(
[Date] float
,[UserName] nvarchar(max)
,[SessionType] int
,[Duration] float
,[MessageCount] int
)
IF EXISTS (SELECT * FROM mytable WHERE [Date] >= 43082 AND [Date] < 43111)
BEGIN
DELETE FROM mytable WHERE [Date] >= 43082 AND [Date]< 43111
;WITH Data AS (
/*do the calculation of data*/
)
INSERT INTO mytable select * from Data
END
ELSE
BEGIN
;WITH Data AS (
/*do the calculation of data*/
)
INSERT INTO mytable select * from Data
END
I have a table with these columns:
id (pk, int identity), imei (varchar), name (varchar), lastconnected (datetime)
Some of the entries in this table have the same name and imei, but different id and different lastconnected date.
How can I effectively filter out all entries that have duplicates (with a SQL script), and then delete the one with the latest lastconnected date?
A simple ROW_NUMBER and DELETE should do the trick:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY imei, [name] ORDER BY lastconnected DESC)
FROM dbo.YourTable
)
DELETE FROM CTE
WHERE RN = 1;
This is easy and will solve your problem
DECLARE #table TABLE
(
id int,
name varchar(10),
imei varchar(10)
)
insert into #table select 1, 'a','a'
insert into #table select 2, 'b','a'
insert into #table select 3, 'c','a'
insert into #table select 4, 'a','a'
insert into #table select 5, 'c','a'
insert into #table select 6, 'a','a'
insert into #table select 7, 'c','a'
insert into #table select 8, 'a','a'
WHILE (exists (select '' from #table group by name , imei having count(*) > 1))
BEGIN
delete from #table where id in (
select max(id) from #table group by imei , name having count(*) > 1)
End
select * from #table
My first instinct is to use RANK(). This will delete all duplicates, not just the most recent, in cases where things are duplicated multiple times.
delete a
from (
select id, imei, name, lastconnected, RANK() over(partition by imei, name order by lastconnected) as [rank] from #temp
) as a
where a.rank>1
It selects the maximum of the date for each combination of name and iemi and then deletes that particular row.
DELETE FROM yourtablee
WHERE (lastconnecteddate,name,imei) in
(SELECT max(lastconnecteddate), name,imei
FROM yourtable
GROUP BY name,imei)
Is there a way to increment an ID field that has a primary key in an INSERT INTO SELECT statement?
What I would want to do is take the last ID of the table and insert an incremented ID with each new record produced by the INSERT INTO SELECT statement?
You can do it like this:
DECLARE #lastId int = 0
SELECT #lastId = MAX(Id) From YourTable
INSERT INTO YourTable (Id, Data)
SELECT (ROW_NUMBER() OVER (ORDER BY (SELECT 0))) + #lastId, at.Data
FROM AnotherTable at
Be sure to add it inside a Transaction scope.
SqlFiddle: http://www.sqlfiddle.com/#!3/d23642/5
Anyway I strongly suggest you to use an IDENTITY column to avoid collisions.
Maybe get the max id and then increse in one on each Insert
INSERT MAX(ID)+1
I think something like this is what you are looking for. Let's assume the PK is an INT for demo purposes.
--Get the last/greatest PK value in first table.
DECLARE #LastPKValue INT
SELECT #LastPKValue = MAX(PKCol)
FROM [schema].[YourTable]
INSERT INTO [schema].[YourTable] (PKCol, ColA, ColB, ColC)
SELECT
ROW_NUMBER() OVER( ORDER BY sot.[SomeColumnName]) + #LastPKValue,
OtherColumnA,
OtherColumnB,
OtherColumnC
FROM [schema].[SomeOtherTable] sot
I have this SQL for creating the procedure:
create procedure [dbo].[spGetProduct](#col_sort varchar(100), #dir_sort varchar(4), #filters nvarchar(max)) as
begin
declare #temp table (
row_num int,
product_id int,
product_name nvarchar(255),
produnit_name nvarchar(50)
)
insert into #temp
EXEC('select * from (select (ROW_NUMBER() OVER (ORDER BY '+#col_sort+' '+#dir_sort+')) row_num, product_id, product_name, dbo.fnGetUnitName(ing_produnit) produnit_name
from dbo.Products
where '+#filters+') as tmp)
select * from #temp
end
Info:
dir_sort can be asc or desc and col_sort is a string that contains one of the column names.
Filters in this case is irrelevant.
When col_sort has the value product_id or product_name it is working fine, but when I call it with produnit_name it throws error.
How can I order the data by that column in this case?
Edit:
The error is:
Invalid column name 'produnit_name'.
You can't reference an alias in the OVER() clause at the same scope, since the alias is defined after the OVER() clause is evaluated. This is the same reason you can't GROUP BY alias or say WHERE alias = 1 - the alias hasn't been defined yet in those cases, either.
If you can't use a join instead of the function to derive the unit name, then you will have to nest again, e.g.
insert into #temp
EXEC('select * from (select (ROW_NUMBER() OVER
(ORDER BY '+#col_sort+' '+#dir_sort+')) row_num, * FROM
(SELECT product_id, product_name,
dbo.fnGetUnitName(ing_produnit) produnit_name
from dbo.Products
where '+#filters+') AS x) as tmp');
That is because produnit_name is a derived column. While you can use a derived column in an ORDER BY clause, you cannot use it with ROW_NUMBER OVER.