nvarchar column to find the previous date in sql - sql

I have followin table schema
declare #temp table
(
id int identity(1,1) not null,
nod nvarchar(50)
)
in which nod column have following data
insert into #temp select 'N/A'
insert into #temp select 'N/A'
insert into #temp select '5'
insert into #temp select 'N/A'
insert into #temp select '7'
insert into #temp select 'N/A'
insert into #temp select '31'
insert into #temp select '15'
i want that select stament shoud give me result on following basis
if nod value 'N/A' then it should show 'N/A'
or if there any numeric value like 5,15,31 then it should show getdate()-nod date date column
I have tried following but fail to minus the days and also represent 'N/A' when 'N/A' in that nvarchar column
select DATEADD(dd,case nod when 'N/A' then 0 else nod end,GETDATE()) from #temp
sql fiddle is here

The following query would return a VARCHAR(50) column that contains either 'N/A' or now - nod date as varchar.
SELECT
CASE nod
WHEN 'N/A' THEN 'N/A'
ELSE CONVERT(VARCHAR(50),
DATEADD(dd,
-1 * CONVERT(INT, nod),
GETDATE()
)
)
END
FROM #temp

Related

Using case in a aggregate sql query without splitting rows

In ms-sql i am using an aggregate group to filter results by user, i would also like to use case to filter by a row not contained in the aggregate so all the user results are on 1 line. I'm not sure this is possible.
Here is the query below which splits the results into two lines.
select case when col_A='1' then sum(col b) End as Sum1_results,
case when col_A='2' then sum(col_b) End as Sum2_Results, Username from tbl1
group by Username, col_A
example of results is.
Sum1_results | Sum2_results | Username
5499 null John
null 3400 John
Ideally, i would like to just have these results merged into one line for each username if possible.
Any help would be appreciated
You could use:
select Username ,
SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,
from tbl1
group by Username
below Query can do the job
Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))
INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')
SELECT * FROM #tmp
select SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp
group by col_A,UserName
DROP TABLE #tmp
Results merged into one line for each username.
Create table #tmp (col_A CHAR(1),col_b int,Username VARCHAR(10))
INSERT INTO #tmp VALUES('1',5000,'John')
INSERT INTO #tmp VALUES('2',400,'John')
INSERT INTO #tmp VALUES('1',499,'John')
INSERT INTO #tmp VALUES('2',3000,'John')
SELECT * FROM #tmp
select SUM(case when col_A='1' then col_b End) as Sum1_results,
SUM(case when col_A='2' then col_b End) as Sum2_Results,Username
from #tmp
group by UserName
DROP TABLE #tmp

SQL windowed function/rownum/order by

I'm trying to see how often a customer has requested Re-Activation of their Internet account.
The problem is, we capture a limited set of data to group on. So my data set is below.
I am trying to Count from the first time a Re-Activation request was created until the First time it was COMPLETED, once it has been completed finish the count of days it took for the request to complete and count the number of NON COMPLETIONS and SENT statuses which occurred between that time.
Below is an image of the sample data as well as the sql for the table. Hope somebody can provide a little help. (using SQL server 2005 compatibility)
CREATE TABLE #temp
(
Identifier varchar(20)NOT NULL
,CreatedDate DATETIME NOT NULL
,CompletedDate DATETIME NOT NULL
,SN_Type varchar(20) NOT NULL
,SN_Status varchar(20) NOT NULL
)
;
INSERT INTO #temp
VALUES('64074558792','20160729','20160805','Re-Activattion','SENT');
INSERT INTO #temp
VALUES('64074558792','20160810','20160810','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES('64074558792','20160812','20160812','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES('64074558792','20160811','20160811','Re-Activattion','COMP');
INSERT INTO #temp
VALUES('64074558792','20160811','20160813','Re-Activattion','N-CO');
INSERT INTO #temp
VALUES ('61030203647','20160427','20160427','Re-Activattion', 'COMP');
INSERT INTO #temp
VALUES('61030203647','20160425','20160425','Re-Activattion', 'N-CO');
INSERT INTO #temp
VALUES('61030203647','20160422','20160422','Re-Activattion', 'N-CO');
INSERT INTO #temp
VALUES('61030203647','20170210','20170210','Re-Activattion', 'COMP');
INSERT INTO #temp
VALUES('61030203688','20170409','20170210','Re-Activattion', 'SENT');
INSERT INTO #temp
VALUES('61030203699','20170409','20170210','De-Activattion', 'COMP');
I am not sure whether this covers your requirement or not,
select identifier,count(1) as cnt,sum(case when sn_status = 'N-CO' then 1 else 0 end) as non_com_cnt ,sum(case when sn_status = 'SENT' then 1 else 0 end) as
sent_cnt, datediff(dd,min(case when sn_status = 'SENT' then createddate end),max(case when sn_status = 'COMP' then completeddate end)) as diff,min(case when sn_status = 'SENT' then createddate end) as start_date,max(case when sn_status = 'COMP' then completeddate end) from #temp where sn_type = 'Re-Activattion' group by identifier;

isnull function does not return correct

When I am using isnull it does not return the '' please see below I have original DOB, isnull used, cast as date.
You would need to convert dob to a char/nchar/varchar/nvarchar type to use isnull() or coalesce() like that.
select isnull(convert(varchar(10),dob,120),'')
if you really would like to return an empty string for the date value, you could try this in a new query window. It creates a table to repoduce your requirement of a null date value and then selects the value before dropping the table.
CREATE TABLE dbo.Test
(
Id INT IDENTITY(1,1) NOT NULL
,Date1 DATE NULL
)
INSERT INTO dbo.Test(Date1) VALUES ('01/01/2017')
INSERT INTO dbo.Test(Date1) VALUES ('01/02/2017')
INSERT INTO dbo.Test(Date1) VALUES (NULL)
INSERT INTO dbo.Test(Date1) VALUES ('01/04/2017')
SELECT * FROM dbo.Test
SELECT Date1 = CASE WHEN date1 IS NULL THEN '' ELSE CAST(DATE1 AS VARCHAR(10)) END from dbo.Test
DROP TABLE dbo.Test
go

sql query serial number

I have written a stored procedure in SQL Server 2000. I want a serial number for output table.
So when I run this stored proc I get this error:
An explicit value for the identity column in table
'#tmpSearchResults1' can only be specified when a column list is used
and IDENTITY_INSERT is ON.
I have tried with set IDENTITY_INSERT #tmpSearchResults1 on
Create Procedure dbo.usp_mobile_All_KeyWord(#searchkey varchar(30))
AS
CREATE TABLE #tmpSearchResults
(
property_id varchar(255),
property_number varchar(255),
auction_date_reason varchar(255)
)
INSERT INTO #tmpSearchResults
SELECT
p.property_id, p.property_number, p.auction_date_reason
FROM
Pr p
INNER JOIN
Au a ON p.auction_id = a.auction_id
INNER JOIN
PrAdd pa ON p.property_id = pa.property_id
INNER JOIN state AS s ON s.state_id=pa.state
where
(
(p.archive = 'N'
AND
a.show_on_site = 'Y'
AND
(
(
((p.auction_date >= CONVERT(datetime, CONVERT(varchar, GETDATE(), 103), 103) and (p.auction_date_reason is null or p.auction_date_reason = ''))
or
(p.auction_date <= CONVERT(datetime, CONVERT(varchar, GETDATE(), 103), 103) and ( p.auction_date_reason = 'Accepting Offers' )))
and
pa.property_address_type_id = 1 )) )
and
(state_abbreviation=#searchkey or s.state_name like '%'+''+ #searchkey +''+'%' or city like '%'+''+ #searchkey +''+'%' or pa.address1 like '%'+''+ #searchkey +''+'%'
or pa.address2 like '%'+''+ #searchkey +''+'%')
)
)
CREATE TABLE #tmpSearchResults1
(
i1 int identity,
property_id varchar(255),
property_number varchar(255),
auction_date_reason varchar(255)
)
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
order by
case when charindex(#searchkey,state) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,statename) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,city) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,address2) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,address1) >0 then 1000 else 0 end desc,
case when charindex(#searchkey,short_description) >0 then 1000 else 0 end desc
select * from #tmpSearchResults1
Plz do help me
The error code is very very very clear.
The relevant portion is ...when a column list is used....
You need to specify your column list in the INSERT statement.
INSERT INTO #tmpSearchResults
(i1,
property_id,
property_number,
auction_date_reason)
SELECT
p.property_id, p.property_number, p.auction_date_reason
FROM...
First, there is a comma too much in the SELECT part of your second statement:
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason , <-- THIS ONE!!
from #tmpSearchResults
The last column of a SELECT statement must be without a comma.
So this would be correct:
insert into #tmpSearchResults1
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
Second, did you read this part of the error message?
An explicit value [...] can only be specified when a column list is used
The "column list" part means that you have to specify the columns in the INSERT part:
insert into #tmpSearchResults1
(property_id, property_number, auction_date_reason)
select
property_id ,
property_number,
auction_date_reason
from #tmpSearchResults
You can get away with not specifying the columns when the number of columns in the SELECT statement is the same as in the table in which they should be inserted (and if the data types match).
If one of these conditions is not met, you need to specify the columns because otherwise SQL Server doesn't know which value to insert into which column.

SQL Server: if "datetime2" < 1753, then "datetime" NULL?

My intention is to insert data from source table into target table. Source table has datetime2 column and target table has datetime column. If datetime2 value does not fit (< year 1753) into datetime field, it will be converted to null. Here is an example
DROP TABLE dbo.test1
--source table
CREATE TABLE dbo.test1 (wday DATETIME2 NULL)
go
INSERT INTO dbo.test1
(wday
)
SELECT '2008-02-01 00:00:00.000'
UNION ALL
SELECT '2009-02-01 00:00:00.000'
UNION ALL
SELECT '0001-02-01 00:00:00.000'
DROP TABLE dbo.test2
--target table
CREATE TABLE dbo.test2 (wday DATETIME NULL)
go
--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
(wday
)
SELECT CASE WHEN DATEDIFF(YEAR, dbo.test1.wday, GETDATE()) < 111
THEN NULL
ELSE CAST(dbo.test1.wday AS DATETIME)
END
FROM dbo.test1
The code does not work. Also using datediff here is not valid logic, how to implement this?
why not just
INSERT dbo.test2
(wday
)
SELECT CASE WHEN dbo.test1.wday < '17530101'
THEN NULL
ELSE CAST(dbo.test1.wday AS DATETIME)
END
FROM dbo.test1
Another option:
--insert only valid datetime dates, < 1753 will be converted to nulls
INSERT INTO dbo.test2
(wday
)
SELECT CASE WHEN DATEPART(YEAR, dbo.test1.wday) < 1753
THEN NULL
ELSE CAST(dbo.test1.wday AS DATETIME)
END
FROM dbo.test1