Error when using insert with CTE and ranking function - sql-server

I have a table temp.Results which contain Employee info. This table contains info used by HR. All changes to the employee records are in the table.i.e.
select * from temp.Results where ID=1
1,'2 main st','salem','2009-01-01','2000-01-01'
1,'34 elm st','acton','2013-03-09','2000-01-01'
Datevalidated is when we entered latest info.DateProcessed is the first time we entered employee info.
WITH ordered as(
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
order by DateValidated desc) as rn from
aa.temp.Results (nolock) where id=31
)
insert into tempResults2(ID, name, address,city, DateValidated, DateProcessed)
select ID, name, address,city, DateValidated, DateProcessed from ordered where rn = 1 ;
I tried getting the above query to get the latest info of each employee into a teable but get this error.
Invalid object name 'tempResults2'
How to resolve this?
Thanks
MR

You can use where clause with select * into .
WITH ordered as
(
select
ID, name, address,city, DateValidated, DateProcessed,
ROW_NUMBER() over (partition by DateValidated order by DateValidated desc) as rn
from aa.temp.Results where id=31
)
select * into tempResults2 from ordered where rn = 1 ;

WITH ordered as(
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
order by DateValidated desc) as rn from
aa.temp.Results (nolock) where id=31
)
select ID, name, address,city, DateValidated, DateProcessed
into tempResults2
from ordered
where rn = 1 ;

You query is wrong. When you can use nolock like this
WITH ordered as(
select ID, name, address,city, DateValidated, DateProcessed
,ROW_NUMBER() over (partition by DateValidated
order by DateValidated desc) as rn from
aa.temp.Results with(nolock) where id=31
)

Related

Average day gap in between a repeat order for each product

Can someone please help me to find the average time between first and second purchase on a product level.
This is what I have written -
Select A.CustomerId,A.ProductId , A.OrderSequence, (Case WHEN OrderSequence = 1 THEN OrderDate END) AS First_Order_Date,
MAX(Case WHEN OrderSequence = 2 THEN OrderDate END) AS Second_Order_Date
From
(
Select t.CustomerId, t.ProductId, t.OrderDate,
Dense_RANK() OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate Asc) as OrderSequence
From Transactions t (NOLOCK)
Where t.SiteKey = 01
Group by t.CustomerId, t.ProductId, t.OrderDate)
A
Where A.OrderSequence IN (1,2)
Group By A.Customer_Id, A.ProductId, A.OrderSequence, A.OrderDate
Sample Data:
It looks like row-numbering and LEAD should do the trick for you here.
Don't use NOLOCK unless you really know what you're doing
It's unclear if you want the results to be partitioned by CustomerId also. If not, you can remove it everywhere in the query
SELECT
A.CustomerId,
A.ProductId,
AVG(DATEDIFF(day, OrderDate, NextOrderDate))
FROM
(
SELECT
t.CustomerId,
t.ProductId,
t.OrderDate,
ROW_NUMBER() OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate) AS rn,
LEAD(OrderDate) OVER (PARTITION BY t.CustomerId, t.ProductId ORDER BY OrderDate) AS NextOrderDate
FROM Transactions t
WHERE t.SiteKey = '01'
) t
WHERE t.rn = 1
GROUP BY
t.Customer_Id,
t.ProductId;

How to Find Ffifth Youngest Employee by DOB in Sql Server

What will be sql query for the fifth youngest employee?
Below query is wrong? please help
SELECT EmpID, EmpName, EMPDOB,
ORDER BY EMPDOB DESC
WHERE ROWNUMBER = 5
FROM dbo.EMP
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY EMPDOB ASC) AS rownumber,
EmpID, EmpName, EMPDOB
FROM EMPLOYEE
) AS foo
WHERE rownumber = 5
The following query will solve your problem:
SELECT TOP 1
T.EmpID
, T.EmpName
, T.EMPDOB
FROM (SELECT TOP 5 * FROM dbo.EMP ORDER BY EMPDOB DESC) AS T
Note: This solution assumes that EMPDOB is in a date or integer based format.

Removing Subqueries

I have 2 tables tab1 and tab2.
tab1:
id name monthid salary inflow
-----------------------------------------
1 mohan 1 2000 1000
1 mohan 3 3000 1000
1 mohan 4 4500 1600
1 mohan 2 2500 1200
in tab2 I want this output:
id name salary inflow
--------------------------
1 mohan 12000 1600
In tab2, salary column is the sum of salary of tab1 and inflow is the inflow of highest month.
I tried this query:
Insert into tab2(id, name, salary)
select id, name, sum(salary)
from tab1
update tab2
set inflow = (select inflow
from tab1
where monthid = max(monthid))
But I know this is not the correct method.
Can anyone help me to correct this query? And I also want to remove the subqueries.
You can use row_number as below
Insert into tab2(id, [name], [salary], inflow)
Select id, [name], Salary, inflow from (
Select id, [name], sum(salary) over(partition by id) as Salary,
inflow, RowN = Row_number() over (partition by id order by monthid desc) from tab1 ) a
Where a.RowN = 1
Without subquery you can use top(1) with ties as below
Insert into tab2(id, [name], [salary], inflow)
Select top (1) with ties id, [name], sum(salary) over(partition by id) as salary, inflow
from tab1
order by Row_number() over (partition by id order by monthid desc)
DECLARE #tab1 table(id int,name varchar(100),monthid int, salary int,inflow int)
INSERT INTO #tab1
SELECT 1,'Mohan',1,2000,1000
UNION ALL
SELECT 1,'Mohan',3,3000,1000
UNION ALL
SELECT 1,'Mohan',4,4500,1600
UNION ALL
SELECT 1,'Mohan',2,2500,1200
SELECT top 1
id, name,SUM(salary) OVER(PARTITION BY id) as salary,MAX(inflow) OVER(PARTITION BY id) as inflow
FROM #tab1
OR
SELECT DISTINCT
id, name,SUM(salary) OVER(PARTITION BY id) as salary,MAX(inflow) OVER(PARTITION BY id) as inflow
FROM #tab1

Count and Row_Number

I want to get the top 5 Zipcodes for each Store with the highest Customers in them (zipcodes).
Please find below my query:
SELECT T.[Store], T.[ZipCode], Count(T.[Customer])
FROM ( SELECT T.[Store], T.[ZipCode],
Count(T.[Customer]) row_number() over (Partition By T.[StoreGitanjali] Order By Count (T.[Customer]) desc) as RN
FROM [Marketing].[dbo].[Poscus] as T
Group By T.[StoreGitanjali], T.[ZipCode]) as T
where T.RN <=5
Group By T.[StoreGitanjali], T.[ZipCode]
Please let me know how to use Count here in this scenario.
Thank you!
Example
CREATE TABLE #t
(
ID INT IDENTITY(1,1),
Customer NVARCHAR(3),
Store NVARCHAR(5),
ZIP INT
)
INSERT INTO #t VALUES('a', 'XYZ', 1234)
,('b', 'XYZ', 1234)
,('c', 'PQR', 1231)
,('d', 'PQR', 1231)
,('e', 'PQR', 1231)
,('f', 'XYZ', 1232)
,('g', 'XYZ', 1232)
,('h', 'XYZ', 1232)
,('i', 'PQR', 1236)
,('j', 'PQR', 1236)
,('k', 'LMN', 1237)
SELECT * FROM #t
The solution is, Set WHERE part < 2 according to your requirement.
SELECT TotalCustomer, Store, ZIP, Part FROM (
SELECT
COUNT(1) AS TotalCustomer,
Store,
ZIP,
ROW_NUMBER() OVER (PARTITION BY Store ORDER BY Store) AS Part
FROM #t
GROUP BY Store, ZIP
) t
WHERE Part < 2
ORDER BY Part
;WITH CTE
AS(
SELECT Store
,Zip
,COUNT(DISTINCT Customer) AS CustCount
FROM #t
GROUP BY Store,Zip
--ORDER BY Store,Zip
)
SELECT A.*
FROM(
SELECT *
--,DENSE_RANK() OVER(PARTITION BY Store ORDER BY CustCount DESC) AS DenRank
,ROW_NUMBER() OVER(PARTITION BY Store ORDER BY CustCount DESC) AS DenRank
FROM CTE
--ORDER BY Store,Zip
) AS A
WHERE A.DenRank <= 2

Performing 'UNION' on the queries with 'ORDER BY'

I am getting a syntax error at the Union all. I know I can't do this. But Can somebody help me out.
SELECT
ID,
date1,
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC ) as RN1,
1 as Range
FROM
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History (nolock)
WHERE [date1] <= CONVERT(DATE,DATEADD(MONTH, -6, GETDATE())) AND
ID in (SELECT txt FROM [dbo].[fn_ListToTable](#listStr, ','))
) AS A ORDER BY date1 DESC, date2 DESC
UNION ALL
SELECT
ID,
Date1,
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC ) as RN1,
1 as Range
FROM
(
SELECT
ID,
date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History (nolock)
WHERE [status_date] <= CONVERT(DATE,DATEADD(MONTH, -3, GETDATE()) -1)
AND
ID in (SELECT txt FROM [dbo].[fn_ListToTable](#listStr, ','))
) AS A ORDER BY date1 DESC,date2 desc
Remove all ORDER BYs from every UNION except the last one and make sure the column names you reference in the ORDER BY correspond to the first SELECT.
There should always one Order by on the very last select of UNION and UNION ALL
SELECT
ID,
date1,
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC ) as RN1,
1 as Range
FROM
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History (nolock)
WHERE [date1] <= CONVERT(DATE,DATEADD(MONTH, -6, GETDATE()))
AND
ID in (SELECT txt FROM [dbo].[fn_ListToTable](#listStr, ','))
) AS A --ORDER BY date1 DESC, date2 DESC Remove order by from here
UNION ALL
SELECT
ID,
Date1,
date2 row_number() OVER (PARTITION BY ID ORDER BY date1 DESC ) as RN1,
1 as Range
FROM
(
SELECT ID,date1,
rn = row_number() OVER (PARTITION BY ID ORDER BY date1 )
FROM listing_History with(nolock)
WHERE [status_date] <= CONVERT(DATE,DATEADD(MONTH, -6, GETDATE()))
AND
ID in (SELECT txt FROM [dbo].[fn_ListToTable](#listStr, ','))
)AS A
ORDER BY date1 DESC, date2 DESC

Resources