why are the results of the two queries different - sql

the first query:
SELECT u.id , prop1.id
FROM ( SELECT '9fbc6e9b59504c08ac643752c1e2d033' AS id ,
'|6813dbbfec6241a19b8d2316d2cb2a65,1|' AS customprop
UNION
SELECT 'f2271c45682f45fc84527c4afff0ab16' AS id ,
'|6813dbbfec6241a19b8d2316d2cb2a65,2|' AS customprop
) u
INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY a.Id ) id ,
A.Id propId ,
B.NAME
FROM ( SELECT '6813dbbfec6241a19b8d2316d2cb2a65' AS id ,
CONVERT(XML, '<v>1,职业资格1</v><v>2,职业资格2</v>') AS value
) A
OUTER APPLY ( SELECT Name = N.v.value('.',
'nvarchar(Max)')
FROM A.[VALUE].nodes('/v') N ( v )
) B
) prop1 ON CHARINDEX('|' + prop1.propid + ','
+ CONVERT(NVARCHAR(10), prop1.id)
+ '|', u.customprop) > 0
GROUP BY u.id ,
prop1.id
the second query:
SELECT u.id ,prop1.id, count(*)
FROM ( SELECT '9fbc6e9b59504c08ac643752c1e2d033' AS id ,
'|6813dbbfec6241a19b8d2316d2cb2a65,1|' AS customprop
UNION
SELECT 'f2271c45682f45fc84527c4afff0ab16' AS id ,
'|6813dbbfec6241a19b8d2316d2cb2a65,2|' AS customprop
) u
INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY a.Id ) id ,
A.Id propId ,
B.NAME
FROM ( SELECT '6813dbbfec6241a19b8d2316d2cb2a65' AS id ,
CONVERT(XML, '<v>1,职业资格1</v><v>2,职业资格2</v>') AS value
) A
OUTER APPLY ( SELECT Name = N.v.value('.',
'nvarchar(Max)')
FROM A.[VALUE].nodes('/v') N ( v )
) B
) prop1 ON CHARINDEX('|' + prop1.propid + ','
+ CONVERT(NVARCHAR(10), prop1.id)
+ '|', u.customprop) > 0
GROUP BY u.id ,
prop1.id
sql can be executed on sqlserver 2005 directly.
the first query can produce one item and the second query produce two items.
I think that the two queries should both produce two items.
I have thouht for three days and I really want to konw why.
I'm a Chinese and my English is poor.I hope you can understand my description

Tough question, but the problem is with this line:
INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY a.Id ) id ,
The ORDER BY is ambiguous and consequently, if it is executed multiple times (which it can be because of the INNER JOIN it is contained in), it may not always return the same ordering/assignment. This can cause a latter join condition to only match on one record instead of two, which is what happens in the query plan being used for the version without the count(*) column.
To fix this, you just need to add something to make the ordering assignment unique, like this:
INNER JOIN ( SELECT ROW_NUMBER() OVER ( ORDER BY a.Id, B.Name ASC ) id ,
Try it like this, it should work.

Your problem is with the ORDER BY clause of the ROW_NUMBER - since the a.ID is not unique the outcome is unpredictable. Make that unique and your problem will go away - you can use something like
...SELECT ROW_NUMBER() OVER ( ORDER BY newid() ) id...

Related

How to fix "ABAP INNER JOIN"

i'm trying to get a inner join from two select sentences but it doesn't work, what i am doing wrong?
i cant work with internal tables because inner join doesn't permit it.
clear: it_spfli.
refresh: it_spfli.
select
spfli-cityto
spfli-cityfrom
into TABLE it_spfli from(select spfli-cityto COUNT( * )from spfli group by spfli-cityto) as t1
INNER JOIN(select spfli-cityfrom COUNT( * )from spfli group by spfli-cityfrom) as t2
ON t1-cityto = t2-cityfrom.
i expect a table of more frequency city to and city from order by city to with table spfli.
First of all i don't think you are doing the right SELECT to get what you want.
I answer this question from the technical perspective. You can use WITH.
WITH +spf1 AS (
SELECT spfli~cityto AS cityto, COUNT(*) AS count FROM spfli GROUP BY spfli~cityto ) ,
+spf2 AS (
SELECT spfli~cityfrom AS cityfrom , COUNT(*) AS count FROM spfli GROUP BY spfli~cityfrom ) ,
+spf3 AS (
SELECT s1~cityto, s2~cityfrom FROM +spf1 AS s1 INNER JOIN +spf2 AS s2
ON s1~cityto = s2~cityfrom )
SELECT * FROM +spf3 INTO TABLE #DATA(lt_result).

(Group By) & (FOR XML PATH) & JOIN

Is there any other approch rather than saving the result of joining (the Table #VT & TableA ) in one Table variable and then from there make the Grouping
select ID ,
STUFF (( select distinct ' / ' + TA.Reason
from #VT
where ( ID = VT.ID )
for xml path(''),TYPE).value('(./text())[1]','VARCHAR(MAX)') ,1,2,'' ) as XXX
from #VT as VT
join TableA as TA on ( TA.ID = VT.ID)
group by ID
I get this Error
Column 'TableA.Reason' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I would go with DISTINCT instead of GROUP BY :
SELECT DISTINCT ID,
STUFF (( SELECT DISTINCT ' / ' + ta.Reason
FROM TableA ta
WHERE vt.ID = ta.ID
FOR XML PATH (''),TYPE).VALUE('(./text())[1]','VARCHAR(MAX)'
), 1, 2, ''
) AS XXX
FROM #VT vt;
I think you have the tables in the wrong place. Does this work?
select ID ,
stuff(( select distinct ' / ' + TA.Reason
from TableA TA
where vt.ID = ta.ID
for xml path(''), TYPE
).value('(./text()) [1]', 'VARCHAR(MAX)') , 1, 2, ''
) as XXX
from #VT vt ;

How to add a temp table in SQL server

I am trying to add a temp table to my query so that I can query that temp table, I have searched the internet but I couldn't get a solution.
this is my query
;WITH cte AS (
SELECT ID, g.Name
FROM game.Game g WITH(NOLOCK
WHERE ID IN (SELECT Data FROM system.Split(1, ','))
UNION ALL
SELECT g.ID, g.Name
FROM game.Game g WITH(NOLOCK)
JOIN cte ON g.ParentID = cte.ID
)
SELECT c.ID,
c.Name
FROM cte c
INNER JOIN list.Type gt WITH(NOLOCK) ON c.TypeId = gt.TypeID
WHERE c.ID NOT IN (SELECT Data FROM system.Split(1, ','))
AND c.ID IN (SELECT ID FROM game.code WITH(NOLOCK)
WHERE ID = c.ID
AND StatusCode IN ('OP', 'CL', 'SU')
AND isDisplay = 'True'
AND GETDATE() BETWEEN DisplayStart AND DisplayEnd
AND GETDATE() < ISNULL(ResultDateTime, ResultExpected)
)
which gives me the following when I run it
ID | Name
1111 | BaseBall
2222 |BasketBall
45896 |Relay
now I tried to create a temp table as follows
Create Table #temp(
ID int,
Name varchar
)
;WITH cte AS (
SELECT ID, g.Name
FROM game.Game g WITH(NOLOCK)
WHERE ID IN (SELECT Data FROM system.Split(1, ','))
UNION ALL
SELECT g.ID, g.Name
FROM game.Game g WITH(NOLOCK)
JOIN cte ON g.ParentID = cte.ID
)
insert into #temp // i wanted to set these values in the temp table
SELECT c.ID,
c.Name
FROM cte c
INNER JOIN list.Type gt WITH(NOLOCK) ON c.TypeId = gt.TypeID
WHERE c.ID NOT IN (SELECT Data FROM system.Split(1, ','))
AND c.ID IN (SELECT ID FROM game.code WITH(NOLOCK)
WHERE ID = c.ID
AND StatusCode IN ('OP', 'CL', 'SU')
AND isDisplay = 'True'
AND GETDATE() BETWEEN DisplayStart AND DisplayEnd
AND GETDATE() < ISNULL(ResultDateTime, ResultExpected)
)
every time I try to store this information in the temp table it gives me an error 'Column name or number of supplied values does not match table definition.' But I only have two values in. What am I doing wrong that I cant see?
First, why not just use select into?
IF OBJECT_ID('TempDB..#temp') IS NOT NULL
BEGIN
DROP TABLE #temp
END
select c.ID, c.Name
into #temp
from . . .
Then you don't need to define #temp as a table.
Next, your definition is bad, because Name has only one character. This would be fixed with select into.
However, I don't know why you are getting the particular error you are getting. The numbers of columns appears to match.

Transposing Rows to Columns and having values flow down in TSQL

I am using TSQL.
If I have the following results:
And I want to transpose this to be like this:
How can I achieve this?
I have the following query:
WITH q AS (
SELECT *
FROM tableOne
WHERE ID = 1
UNION ALL
SELECT m.*
FROM tableOne m
JOIN ON m.ParentID = q.ID
)
SELECT *
FROM q
This gives me all of the items underneath the specified node including the specified node.
It could be easy for us to help you if you add scripting data and not an image. Note that tbl is the name of your table, it is called 3 times. Try this:
select
a.fieldValue company,
b.fieldValue department,
c.fieldValue Job
from tbl a
inner join tbl b on a.parentId is null and a.id=b.parentID
inner join tbl c on b.id= c.parentID
If it does not bring desired results please add data as text and let me know, I could modify the query
Another option (assuming this is NOT a jagged hierarchy).
This is a standard Recursive CTE, with a little twist in the final SELECT
Example
;with cteP as (
Select ID
,ParentID
,PathID = cast(FieldValue as varchar(max))
From YourTable
Where ParentID is Null
Union All
Select ID = r.ID
,ParentID = r.ParentID
,PathID = cast(p.PathID+'|||'+r.FieldValue as varchar(max))
From YourTable r
Join cteP p on r.ParentID = p.ID)
Select ID
,B.*
From cteP A
Cross Apply (
Select Company = xDim.value('/x[1]','varchar(max)')
,Department = xDim.value('/x[2]','varchar(max)')
,Job = xDim.value('/x[3]','varchar(max)')
From (Select Cast('<x>' + replace(PathID,'|||','</x><x>')+'</x>' as xml) as xDim) as X
) B
Where ID not in (Select Distinct ParentID from YourTable where ParentID is not null)
Order By PathID
Returns

How can i eliminate dups?

select C.Id as candidateId,C.Name, C.Phone, Status.ResultStatusText , Status.TimeStamp, Status.notes ,
(Select count(*) from CandidateCallHistory where CandiateId = candidateId) AS numbCalls,
(SELECT SUBSTRING((SELECT ',' + Name
FROM Jobs
WHERE Id in (select value from fn_Split(c.JobIds,','))
FOR XML PATH('')),2,200000)) AS jobsList
from Candidate2 C
outer APPLY (select top 1 CH.CandiateId, CH.ResultStatusText , CH.TimeStamp , CH.notes
from CandidateCallHistory CH
where CH.CandiateId = C.Id
order by TimeStamp desc) as Status
where Status.ResultStatusText <> 'completed' and Status.ResultStatusText <> 'canceled' and c.isactive = 1
I have multiple records in the CandidateCallHistory table and seems this is causing issue with the outer apply ( i may be wrong) as it should only get the most recent record in the table since it selects top 1.
Try to add distinct in first line after select:
select distinct [...]