SQL Joining from 2 fields to a concatenated field - sql

I have a quote ID field in a table (PING) that has the following format: "XX" (which is just a lead off to the quote number) followed by the USERID "YYYY" and then the Cart_ID "ZZZZ". Both of the second fields come from another table (Cart). I need to join Cart to the first table. These 2 fields are the only way to join them, but I can't figure out how to join 2 fields to 1 field from another table. Obviously code below won't work, but is for illustration.
join PROD..CART on Cart.CART_ID and Cart.USERID = CW_PING.QuoteID

Try this:
join PROD..CART on CONCAT(Cart.CART_ID,Cart.USERID) = CW_PING.QuoteID

This was the final solution:
join PROD_QQ..CART on 'QQ' + (right('0000000000' + CAST (Cart.USERID as varchar),4) + (right( '0000000000' + CAST (Cart.CART_ID as varchar),6)))

try:
join PROD..CART on [Cart.CART_ID + Cart.USERID] = CW_PING.QuoteID

Related

Pentaho CDE SQL Query with numerical param

I would like to know if it is possible to perform an SQL query and pass it a numerical parameter. Let's suppose that I have the following query:
SELECT
CONCAT(cuatrimestre,' Cuatrimestre') As quarter
, ROUND(SUM(fact_Ventas.cantidad * precioUnitario),0) as amount
FROM fact_Ventas
INNER JOIN dim_Tiempos ON
fact_Ventas.idAnio = dim_Tiempos.idAnio AND
fact_Ventas.idMes = dim_Tiempos.idMes AND
fact_Ventas.idDia = dim_Tiempos.idDia
INNER JOIN dim_Clientes ON dim_Clientes.idCliente = fact_Ventas.idCliente
INNER JOIN dim_Productos ON dim_Productos.idProducto = fact_Ventas.idProducto
WHERE
CAST(fact_Ventas.idAnio As Char) LIKE ${paramAnio} AND
CAST(fact_Ventas.idMes As Char) LIKE ${paramMes} AND
CAST(fact_Ventas.idVendedor As Char) LIKE ${paramVendedores} AND
CAST(fact_Ventas.origen As Char) LIKE ${paramOrigen} AND
dim_Productos.marca LIKE ${paramMarca} AND
dim_Clientes.segmentoCliente LIKE ${paramSegmento}
GROUP BY 1
ORDER BY 1
I want to divide the column amount, by a numerical value extracted from a simple parameter. I managed to use filters in the where clause, but I can not make a division in a column.
Try the following query:
SELECT
CONCAT(cuatrimestre,' Cuatrimestre') As cuatrimestre
, ROUND( (SUM(fact_Ventas.cantidad * precioUnitario)/${paramValue}),0) as Importe
FROM fact_Ventas
INNER JOIN dim_Tiempos ON
fact_Ventas.idAnio = dim_Tiempos.idAnio AND
fact_Ventas.idMes = dim_Tiempos.idMes AND
fact_Ventas.idDia = dim_Tiempos.idDia
INNER JOIN dim_Clientes ON dim_Clientes.idCliente = fact_Ventas.idCliente
INNER JOIN dim_Productos ON dim_Productos.idProducto = fact_Ventas.idProducto
WHERE
CAST(fact_Ventas.idAnio As Char) LIKE ${paramAnio} AND
CAST(fact_Ventas.idMes As Char) LIKE ${paramMes} AND
CAST(fact_Ventas.idVendedor As Char) LIKE ${paramVendedores} AND
CAST(fact_Ventas.origen As Char) LIKE ${paramOrigen} AND
dim_Productos.marca LIKE ${paramMarca} AND
dim_Clientes.segmentoCliente LIKE ${paramSegmento}
GROUP BY 1
ORDER BY 1
But it gives an error and the data is not loaded. The syntax of the query was tested in the database and is correct.
Did you set the parameter type to Numeric? It defaults to String which was probably fine for your other parameters.
The problem was that I forgot to assign the parameter to the component, I had associated it with SQL Query but not with the component.

SQL Server: Conversion failed when converting the varchar value '1,2'

I have a query like this
select
t.tiid, t.employeeid, t.remarks,
dd.DocID, dd.Document, dd.DocuName
from
ti t
inner join
History cth on cth.tiid = t.tiid
inner join
Downloads dd on dd.DocID = cth.DocID
My data in table is like this
History:
DocID DocuName
1,2 abc.dox,def.docx
Downloads
DocID DocuName document
1 abc.docx x3400000efg..
2 def.docx xc445560000...
but when I execute this query, it shows an error:
Conversion failed when converting the varchar value '1,2' to data type int.
The DocID of history is multiple DocID had been combined with comma, So you can not compare the value directly( One value vs Multiple values).
You can check whether the multiple values contain the specify value use CHARINDEX.
To make sure complete matched of sub string,need a delimiter to indicate a single value, otherwise can get wrong result.
For Eample:
CHARINDEX('1,','12,2,3') will be 1, but in fact, there is no 1 in the string.
select
t.tiid,
t.employeeid,
t.remarks,
dd.DocID,
dd.Document,
dd.DocuName
from ti t
inner join History cth on cth.tiid=t.tiid
inner join Downloads dd on CHARINDEX(','+LTRIM(dd.DocID)+',',','+cth.DocID+',')>0
As the error says, you are trying to equate a string with int.You need to convert the int DocID as string and check if it's present in the comma-separated DocID .Something like
SELECT t.tiid,
t.employeeid,
t.remarks,
dd.DocID,
dd.Document,
dd.DocuName
FROM ti t
INNER JOIN History cth ON cth.tiid=t.tiid
INNER JOIN Downloads dd ON CHARINDEX(',' + CAST(dd.DocID AS VARCHAR(10)) + ',',',' + cth.DocID + ',')>0

How can I run a SQL query iteratively for every row in a table?

I have the following query:
DECLARE #AccString varchar(max)
SET #AccString=''
SELECT #Acctring=#AccString + description + ' [ ] '
FROM tl_sb_accessoryInventory ai
JOIN tl_sb_accessory a on a.accessoryID = ai.accessoryID
WHERE userID=6
SELECT userID, serviceTag, model, #AccString AS ACCESSORIES FROM tl_sb_oldLaptop ol
JOIN tl_sb_laptopType lt ON ol.laptopTypeID = lt.laptopTypeID
WHERE userID=6
which outputs this:
What I want to be able to do is run this for every userID in a table tl_sb_user.
The statement to get the userIDs is:
Select userID from tl_sb_user
How can I get this to output a row as above for each user?
You are trying to do a string concatenation subquery. In SQL Server, you need to do the string concatenation using a correlated subquery with for xml path. Arcane, but it generally works.
The results is something like this:
SELECT userID, serviceTag, model, #AccString AS ACCESSORIES,
stuff((select ' [ ] ' + description
from tl_sb_accessoryInventory ai join
tl_sb_accessory a
on a.accessoryID = ai.accessoryID
where a.userId = ol.UserId
for xml path ('')
), 1, 11, '') as accessories
FROM tl_sb_oldLaptop ol JOIN
tl_sb_laptopType lt
ON ol.laptopTypeID = lt.laptopTypeID;
You don't have table aliases identifying where the columns come from, so I am just guessing that a.userId = ol.UserId references the right tables.
Also, this substitutes certain characters with html forms. Notably '<' and '>' turn into things like '<' and '>'. When I encounter this problem, I use replace() to replace the values.
Simply leave out the WHERE clause.

SQL CONCAT IF Statement?

Morning All,
Im not to sure how i need to solve my following query... I have the following query which pulls back the desired records in SQL server...
SELECT agenda.AgendaItemNumber,Agenda.AgendaName, AgendaType.AgendaTypeDescription, userdetails.fullName
FROM Agenda
JOIN AgendaType ON AgendaType.AgendaTypeID=Agenda.AgendaTypeID
JOIN UserDetails ON Agenda.AgendaID = Userdetails.AgendaID
WHERE agenda.AgendaTypeID = '2'
AND AgendaItemNumber = AgendaItemNumber
AND AgendaName = AgendaName
AND AgendaTypeDescription = AgendaTypeDescription
AND AgendaItemNumber >= '3'
The above query works but i need to enhance this slightly. It pulls back the following results, which essentially are duplicate records except for the 'fullname' column...
What i would like to do is be able to add some extra code to this query so that when i run the query i am able to display one record for each 'AgendaItemNumber' and for it to concat both of the fullnames for this record. However i have additional AgendaItemsNumbers in this table that only have 1 x user fullname assigned to them. its just these few records within the image file i need to do something clever with.
Maybe there is a better way to complete this task?
Many thanks in advance. Any queries please dont hesitate to ask.
Regards
Betty
SELECT agenda.AgendaItemNumber,
Agenda.AgendaName,
AgendaType.AgendaTypeDescription,
STUFF(( SELECT ';' + FullName
FROM UserDetails
WHERE UserDetails.AgendaID = Agenda.AgendaID
FOR XML PATH('')
), 1, 1, '') AS fullName
FROM Agenda
INNER JOIN AgendaType
ON AgendaType.AgendaTypeID=Agenda.AgendaTypeID
INNER JOIN UserDetails
ON Agenda.AgendaID = Userdetails.AgendaID
WHERE agenda.AgendaTypeID = '2'
AND AgendaItemNumber = AgendaItemNumber
AND AgendaName = AgendaName
AND AgendaTypeDescription = AgendaTypeDescription
AND AgendaItemNumber >= '3'
ADENDUM
The XML extension in SQL-Server allows you to concatenate multiple rows into a single row. The actual intention of the extension is so you can output as XML (obviously), but there are some nifty tricks that are byproducts of the extensions. In the above query, if there were a column name in the subquery (FullName) it would output as <FullName>Joe Bloggs1</FullName><FullName>Joe Bloggs2</FullName>, because there is no column name it simply concatenates the rows (not forming proper XML). The PATH part allows you to specify an additional node, for example if you use PATH('Name') in the above you would get <Name>;Joe Bloggs</Name><Name>;Joe Bloggs2</Name> If you combine Path with a column name you would get Joe Bloggs.
Finally the STUFF just removes the semicolon at the start of the list.

naming columns in excel with Complex sql

I’m trying to run this SQL using get external.
It works, but when I try to rename the sub-queries or anything for that matter it remove it.
I tried as, as and the name in '', as then the name in "",
and the same with space. What is the right way to do that?
Relevant SQL:
SELECT list_name, app_name,
(SELECT fname + ' ' + lname
FROM dbo.d_agent_define map
WHERE map.agent_id = tac.agent_id) as agent_login,
input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
FROM dbo.maps_report_list list
JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id)
WHERE input = 'SYS_ERR'
AND app_name = 'CHARLOTT'
AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
AND list_name LIKE 'NRBAD%'
ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970'))
You could get rid of your dbo.d_agent_define subquery and just add in a join to the agent define table.
Would this code work?
select list_name, app_name,
map.fname + ' ' + map.lname as agent_login,
input,
convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds
from dbo.maps_report_list list
join dbo.report_tac_agent tac
on (tac.list_id = list.list_id)
join dbo.d_agent_define map
on (map.agent_id = tac.agent_id)
where input = 'SYS_ERR'
and app_name = 'CHARLOTT'
and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%'
order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem.
I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
To remove the sub query in the SELECT statement I suggest the following:
SELECT list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss, TAC_BEG_tstamp, '01/01/1970))
FROM dbo.maps_report_list inner join
(dbo.report_tac_agent as tac inner join dbo.d_agent_define as map ON (tac.agent_id=map.agent_id)) ON list.list_id = tac.list_id
WHERE input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008'
and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970'))
I used parentheses to create the inner join between dbo.report_tac_agent and dbo.d_agent_define first. This is now a set of join data.
The combination of those tables are then joined to your list table, which I am assuming is the driving table here. If I am understand what you are trying to do with your sub select, this should work for you.
As stated by the other poster you should use table names on your columns (e.g. map.fname), it just makes things easy to understand. I didn't in my example because I am note 100% sure which columns go with which tables. Please let me know if this doesn't do it for you and how the data it returns is wrong. That will make it easier to solve in needed.