How to use split.item in SQL, spliting cols by commas - sql

I'm getting the error:
"The multi-part identifier "split.item" could not be bound."
Pretty much I'm going to make a third table with each individual person this is just an example:
SELECT
split.item as memberID
FROM
tics T
JOIN
mem M
ON
m.memberId = split.item
CROSS APPLY
dbo.Splitstring(t.Resources,',') AS split

You have the join in wrong order, you can't refer to something that comes later in the SQL, in this case "m.memberId = split.item" since split is the next item you're adding there. The correct way to do this is:
SELECT
split.item as memberID
FROM
tics T
CROSS APPLY dbo.Splitstring(t.Resources,',') AS split
JOIN mem M ON m.memberId = split.item

Related

How to only select an attribute one time

This code shows me the results based on two tables
SELECT h.Destino, g.Fuente
FROM Hist_LDS h, gTronco g
WHERE h.Fecha='2020-10-28'
AND g.Tronco = h.Tronco
The Destinos are 19 and then it repeat, i need to only apeers one time, and count the time od appereance to. I need to create a new table when insted of the information in the variable Tronco I put the Destino and Fuente
What you are doing is a CROSS JOIN.
And what you probably want is a simple INNER JOIN. Not very clear from your question, also check LEFT/RIGHT JOIN.
SELECT h.Destino, g.Fuente
FROM Hist_LDS h
INNER JOIN gTronco g ON g.Tronco = h.Tronco
WHERE h.Fecha='2020-10-28'

Replace row with Column Data in Sql Server

I have a table with some data and I was trying to Replace the Column with Row.
SELECT Handset_UID, [IMEI_NO_1] AS [IMEI #1],[IMEI_NO_2] AS [IMEI #2],
Isnull(Convert(varchar,Mfg_Date,106),'Not Found') as [Mfg. Date]
FROM stock.Handset a
join Stock.Model b
on a.Model_ID = b.Model_ID
JOIN Stock.Brand C
ON A.Brand_ID = C.Brand_ID
where a.Handset_UID = 'GFI13508637275434'
The above Query gives me the result in one single row data.
But I want the Result in below format
I have tried the Pivot Operator using Derived Column but got confused during implementation.
Please help to get the correct query.
Assuming that you are running SQL Server, as the syntax suggests, you can unpivot with cross apply:
select x.col, x.val
from stock.handset h
inner join stock.model m on h.model_id = m.model_id
inner join stock.brand b on on h.brand_id = b.brand_id
cross apply (values
('handset_uid', handset_uid),
('IMEI #1', imei_no_1),
('IMEI #2', imei_no_2),
('Mfg.Date', convert(varchar, Mfg_Date, 106), 'Not Found')
) x(col, val)
where h.handset_uid = 'gfi13508637275434'
Side notes:
meaningful table aliases make the query easier to read and write
your query has many columns that are not qualified with the alias of the table they belong to, which makes your query rather unclear about the underlying structure; I would strongly recommend that you qualify all columns in the query

Nesting multiple same select queries and reuse without second round trip to database

I am having a rows with two different IDs in database. Now I am trying to show two different data columns in one row, I tried something like this:
SELECT
[dbo].[fnHexToNumber]([Participant].[Stake]) AS [PlayerStake],
(SELECT [dbo].[fnHexToNumber]([Stake])
FROM [dbo].[Participant_Complete]
WHERE [ParticipantId] = [Fold].[HouseParticipantId]) AS [HouseStake],
([dbo].[fnHexToNumber]([Participant].[Stake]) + [dbo].[fnHexToNumber]([C].[RunningWinLoss])) AS [PlayerStakeAfterRound],
(SELECT [dbo].[fnHexToNumber]([Stake])
FROM [dbo].[Participant_Complete]
WHERE [ParticipantId] = [Fold].[HouseParticipantId]) - [dbo].[fnHexToNumber]([C].[RunningWinLoss]) AS [HouseStakeAfterRound]
FROM
[dbo].[Round_Complete] AS [C]
INNER JOIN
[dbo].[Fold_Complete] AS [Fold] ON [Fold].[Id] = [C].[Id]
INNER JOIN
[dbo].[Participant_Complete] AS [Participant] ON [Participant].[ParticipantId] = [Fold].[PlayerParticipantId]
This works, but as you can see it will do two trips to database for same nested select. How can I make this only one round trip?
You are referring to the subqueries. That is not a "round trip to the database", which usually refers to an application calling a query.
All the square braces make the query hard to read, but you can fix this using apply:
SELECT [dbo].[fnHexToNumber](p.[Stake]) AS PlayerStake,
h.HouseStake,
([dbo].[fnHexToNumber](p.[Stake]) + [dbo].[fnHexToNumber]([C].RunningWinLoss)) AS PlayerStakeAfterRound,
(h.HouseStake - [dbo].fnHexToNumber(C.RunningWinLoss)) AS HouseStakeAfterRound
FROM [dbo].[Round_Complete] c JOIN
[dbo].[Fold_Complete] f
ON f.[Id] = c.[Id] JOIN
[dbo].[Participant_Complete] pc
ON px.[ParticipantId] = f.[PlayerParticipantId] OUTER APPLY
(SELECT [dbo].[fnHexToNumber]([Stake]) as HouseStake
FROM [dbo].[Participant_Complete] pch
WHERE pch.ParticipantId = f.HouseParticipantId
) h
Just join the same table a second time instead of pulling the data as sub-queries.
Also, you only need brackets around names if the names contain a space (which is bad practice in general). If the names don't have a space, the brackets are totally extraneous.
SELECT
dbo.fnHexToNumber(Participant.Stake) AS PlayerStake,
dbo.fnHexToNumber(p.Stake) as HouseStake,
(dbo.fnHexToNumber(Participant.Stake) + dbo.fnHexToNumber(C.RunningWinLoss)) AS PlayerStakeAfterRound,
dbo.fnHexToNumber(p.Stake) - dbo.fnHexToNumber(c.RunningWinLoss) as HouseStakeAfterRound
FROM dbo.Round_Complete AS C
INNER JOIN dbo.Fold_Complete AS Fold
ON Fold.Id = C.Id
INNER JOIN dbo.Participant_Complete AS Participant
ON Participant.ParticipantId = Fold.PlayerParticipantId
INNER JOIN dbo.Participant_Complete AS p
ON p.ParticipantId = Fold.HouseParticipantId

CONCAT value in ON condition of JOIN

I have two tables.
Table: Geonames:
Country (2 character ISO code, e.g. SE)
AdminArea (Char code, e.g. 0330)
Table AdminAreas
AdminCode, (Combination of Coutry and AdminArea, e.g. "SE.0330")
So the ID of the AdminAreas that I want to join the tables on is a combination of columns on the first table. To join it I will need to join the two values from the Geonames table. Something like.
SELECT
geoname.geonameid, geoname.name, geoname.latitude, geoname.longitude,
geoname.country, geoname.admin1, admin_one.admin_id, admin_one.geoname_id
FROM geoname
INNER JOIN admin_one ON admin_one.admin_id = CONCAT(geoname.country, '.', geoname.admin1)
WHERE country='SE' LIMIT 10
Unfortunately, this is not working. It does not seem like i can CONCAT or do string_agg() on a JOIN. How do I get this JOIN working?
Your code is fine. Perhaps one issue is that you have spaces or some other character. I would recommend investigating this using:
SELECT gn.geonameid, gn.name, gn.latitude, gn.longitude,
gn.country, gn.admin1, ao.admin_id, ao.geoname_id
FROM geoname gn LEFT JOIN
admin_one ao
ON ao.admin_id = CONCAT(TRIM(gn.country), '.', TRIM(gn.admin1))
WHERE gn.country = 'SE'
LIMIT 10;
This will return even unmatched results (because of the LEFT JOIN). That might help you investigate the issue.

set a variable in outer apply statement sql

I want to get one row in Outer apply statement for one of task Id, but SQL be angry me in outer apply statement with red line :) Any ideas ?
declare #OwnerUserIDs as Nvarchar(max)
select bt.*
,cu.NAME+' '+cu.SURNAME as OwnerUserName
,cu2.NAME+' '+cu2.SURNAME as CreatedUserName
,T.Data
from Business_Tasks(nolock) bt
left join CommmerceCoreReleaseV1..CORE_USERS(nolock) cu on cu.USERID=bt.OwnerUserID
left join CommmerceCoreReleaseV1..CORE_USERS(nolock) cu2 on cu2.USERID=bt.CreatedUserID
outer apply
(
SELECT #OwnerUserIDs = Data from ( select COALESCE(#OwnerUserIDs + ';', '') + convert(nvarchar,bto.ownerUserID) as Data from Business_TasksOwner(nolock) bto where bto.TaskID=13)
) T
where bt.IsActive=1 and bt.ID=13
Answer
Hi, I found the answer, i changed inside of outer apply statement :
select bt.*
,cu.NAME+' '+cu.SURNAME as OwnerUserName
,cu2.NAME+' '+cu2.SURNAME as CreatedUserName
,T.OwnerUserIDs
from Business_Tasks(nolock) bt
left join CommmerceCoreReleaseV1..CORE_USERS(nolock) cu on cu.USERID=bt.OwnerUserID
left join CommmerceCoreReleaseV1..CORE_USERS(nolock) cu2 on cu2.USERID=bt.CreatedUserID
outer apply
(
select STUFF((SELECT ';'+ convert(nvarchar,bto.OwnerUserID)
FROM Business_TasksOwner(nolock) bto
where bto.TaskID=bt.ID
FOR XML PATH('')), 1, 1, '') AS OwnerUserIDs
) T
where bt.IsActive=1 and bt.ID=13
Okay, there are a few issues with your query as it stands:
you need to add an alias name to your inner query, the one that starts "SELECT COALESCE...", i.e. put a letter, say X, after "bto.TaskId = 13)".
you can't set your variable to the results of this sub-query the way you have, if you remove the "#OwnerUserIDs = " bit then your query should compile;
I don't understand what your OUTER APPLY is trying to achieve, surely it will just return the same results for every row returned, i.e. where TaskId = 13? Maybe this should be referring to the main query in some way?
If you want to set the #OwnerUserIDs to be the concatenated results of the OwnerUserIDs then you need to use a different mechanism, either a recursive CTE or XML PATH query would work.
I would try to rewrite your query for you but I am not sure what you are trying to achieve here. I guess you want to end up with a list of User Ids in #OwnerUserIDs but I'm not sure what the rules should be...