SQL Server 2014 UNION in CROSS APPLY - sql-server

I have the following query
SELECT DISTINCT
d.UserName,
i.itemID,
d.Score,
d.StoreCode,
d.Location
FROM
G.dbo.Users d
LEFT JOIN
G.dbo.Emails s on d.UserName=s.UserName
CROSS APPLY
(
SELECT TOP (1)
ii.ItemID
FROM
G.dbo.Dump ii
WHERE
ii.Username=d.UserName
AND
ii.endTime>DATEADD(hh,3,getDate())
) i
WHERE
s.serName is null
AND
d.Score>#_Score
AND
(d.processed=0)
GROUP BY
d.UserName,
i.itemID,
d.Score,
d.StoreCode,
d.Location
ORDER BY
d.UserName ASC
Now I need to modify it since Table G.dbo.Dump has been splitted into 20 smaller tables and now I have Dump_00 to Dump_19
I try to modify part of the CROSS APPLY section using UNION in this way
CROSS APPLY
(
SELECT TOP (1)
ii.ItemID
FROM
(
SELECT TOP (1) FROM G.dbo.Dump_00
UNION
SELECT TOP (1) FROM G.dbo.Dump_01
UNION
.....
SELECT TOP (1) FROM G.dbo.Dump_19
) ii
WHERE
ii.UserName=d.UserName
AND
ii.EndTime>DATEADD(hh,3,getDate())
) i
but result is not working as expected
can suggest if UNION is the right way and in case how to apply, or another solution?
Thanks!

Remove the TOP 1 from the union elements. Not sure why that was added. Logically, you are after a set that is the union of all tables.
Also, I don't think you want a union at all. You want the concatenation.
CROSS APPLY
(
SELECT TOP (1) ii.ItemID
FROM
(
SELECT FROM G.dbo.Dump_00 --changed
UNION ALL --changed
SELECT FROM G.dbo.Dump_01 --changed
.....
) ii
) i

Related

SQL Data Hierarchy Mapping

The first data table shows the hierarchy structure and Im trying to show how each level relates to all the children underneath. The output I'm looking for is the second table.
Any pointers of how to do this in T-SQL please?
A recursive CTE is what you use to get this output:
WITH reccte AS
(
/*Recursive Seed (first result set upon which we iterate)*/
SELECT CUSTOMERNO, CUSTOMER_PARENT, HIERARCHY
FROM yourtable
WHERE CUSTOMERNO NOT IN (SELECT CUSTOMER_PARENT FROM yourtable)
UNION ALL
/*Recursive Member - The part that refers to itself that iterates until the join fails*/
SELECT
reccte.CUSTOMERNO, yourtable.CUSTOMER_PARENT, yourtable.HIERARCHY
FROM reccte
INNER JOIN yourtable
ON reccte.CUSTOMER_PARENT = yourtable.CUSTOMERNO
)
/*select from the CTE output*/
SELECT * FROM reccte
UNION ALL
/*Union in those level 0 records (records that aren't a parent themselves*/
SELECT CUSTOMERNO, CUSTOMERNO, 0 FROM yourtable WHERE CUSTOMERNO NOT IN (SELECT CUSTOMER_PARENT FROM yourtable)

sql server using recrusive cte to get the level in the same group

I have a sql server table showing the IDs and their previous IDs,
create table test2 ( ID varchar(10) ,
Pre_ID varchar(10)
)
insert into test2 values ('e','d')
, ('d','c')
, ('c','b')
, ('b','a')
, ('a',null)
, ('r','q')
, ('q','p')
, ('p',null)
the table is like this:
The result should be like this:
I have successfully got the levels using a recursive cte, but could not get the correct group for them. can anyone help? Thanks.
This is my code:
with cte as (
select id, Pre_ID, level
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id
What you need to do is start with the first level and add a ROW_NUMBER to that, then join all further levels recursively:
with cte as (
select id, Pre_ID, level, row_number() over (order by ID) as grp
from #temp2
where Pre_ID is null
union all
select t2.id, t2.Pre_ID, t2.level, cte.grp
from cte
inner join #temp2 t2
on t2.Pre_ID=cte.id
)
select * from cte
order by id;

Transforming and repeating multiple rows

I have a table that has two IDs within it named FamilyID and PersonID. I need to be able to repeat these rows with all combinations, as the below screenshot shows noting that each of the numbers get an extra row.
Here is some SQL to create the table with some sample data. There is no set number of occurrences that could occur.
Anyone aware of how we could be achieved?
CREATE TABLE #TempStackOverflow
(
FamilyID int,
PersonID int
)
insert into #TempStackOverflow
(
FamilyID,
PersonID
)
select
1012,
1
union
select
1013,
1
union
select
1014,
1
union
select
1015,
2
union
select
14774,
3
union
select
1019,
5
I understand that you need some sort of a complete list of matches within groups, but honestly, it would be much better if you would explain the business context, using plain English, in the first place.
The following query seems to produce your sample result:
with cte as (
select a.FamilyID, a.PersonID, a.PersonID as [GroupId] from #TempStackOverflow a
union all
select b.PersonID, b.FamilyID, b.PersonID from #TempStackOverflow b
)
select distinct c.FamilyID, s.PersonID
from cte c
inner join cte s on s.GroupId = c.GroupId
where c.FamilyID != s.PersonID;
Here is the simplest version I can come up with that groups the items by PersonId, as you do above. Obviously if you don't want that, then you can remove the outer query.
SELECT FamilyId,
PersonID
FROM (
SELECT FamilyId, PersonId, PersonID as SortBy
FROM #TempStackOverflow t1
UNION
SELECT PersonId, FamilyId, PersonId as SortBy
FROM #TempStackOverflow t1
UNION
SELECT t1.FamilyID, t2.FamilyID, t1.PersonID as SortBy
FROM #TempStackOverflow t1
FULL OUTER JOIN #TempStackOverflow t2
ON t1.PersonID = t2.PersonID
WHERE t1.FamilyID != t2.FamilyID
) as Src
ORDER BY SortBy

USING IF WITH OUTER APPLY IN MSSQL

I want to write IF conditition in OUTER APPLY. I need to return more than one column so i don't want to write subqueries
SELECT name FROM v_users
OUTER APPLY
(
IF CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)
SELECT gender,email,age,class FROM tb_register_old WHERE id=v_users.user_id;
ELSE
SELECT gender,email,age,class FROM tb_register_new WHERE id=v_users.user_id;
)s
Maybe this?
SELECT name FROM v_users
OUTER APPLY
(
SELECT gender,email,age,class
FROM tb_register_old
WHERE id=v_users.user_id and CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)
UNION ALL
SELECT gender,email,age,class
FROM tb_register_new
WHERE id=v_users.user_id and CAST(reg_date AS DATE) >= CAST('03/25/2017' AS DATE)
)s

IN NOT IN SQL Server 2005

How can I see what is not in the table... I know I know...can only see what is there but come on!!!
So!!
select * from ORDER where State IN ('MA','PA','GA','NC')
So I will get MA and PA but I want to see GA and NC....
NOT IN will return NY,NJ,CT ect.... I just want to see what is in the ( )
It looks like you are missing a single quote ' in front of GA.
My understanding of the question is: For a given list of states, which ones do not exist in the Order table?
This will show you what states out of the four listed below have no corresponding records in the Order table:
select distinct s.State
from
(
select 'MA' as State
union all
select 'PA'
union all
select 'GA'
union all
select 'NC'
) s
left outer join [Order] o on s.State = o.State
where o.State is null
I'm going to try to read between the lines a little here:
;with cteStates as (
select 'MA' as state
union all
select 'PA'
union all
select 'GA'
union all
select 'NC'
)
select s.state, count(o.state) as OrderCount
from cteStates s
left join [order] o
on s.state = o.state
group by s.state
Are you just trying to find out which states there are except for those four? If so:
SELECT DISTINCT State FROM dbo.ORDER WHERE State NOT IN ('MA', 'PA', 'GA', 'NC')

Resources