SQL passing table column to a function parameter - sql-server-2008

I wish to call my function (dbo.Split) with a column table (U.UbicacionF) but it doesn't work! Please can u help me!! Thanks
SELECT
EE.IDEstatus, EE.IDAsignacion,EE.IDUNIDAD,
EE.IDEQUIPO,EE.ESTATUS,EE.bUltEstatus,
A.IDDestino, U.UbicacionF, TI.Tiempo
FROM
mar_EstatusEquipo EE
LEFT JOIN
mar_Asignaciones A ON EE.IDAsignacion = A.IDAsignacion
AND EE.IDUNIDAD = A.IDUNIDAD
LEFT JOIN
mar_TmpUbicaciones U ON EE.IDUNIDAD = U.IdUnidad AND U.IdUnidad = A.IDUNIDAD
LEFT JOIN
mar_TiemposArriboPto TI ON A.IDDestino = TI.Destino
AND TI.Ubicacion LIKE '%' + (SELECT *
FROM dbo.Split(U.UbicacionF, ',', '1')) + '%'
WHERE
EE.IDEquipo = CAST(EE.IDUNIDAD AS CHAR)
AND EE.Estatus IN ('IT','ET')
AND A.IDDestino = 'MZO'
AND EE.bUltEstatus = 1
AND EE.IDUNIDAD = 255
ORDER BY
EE.IDUNIDAD

You could use an APPLY operator to pass a column to a table-valued function like that. In your case it would rather be OUTER APPLY than CROSS APPLY, to match your current outer join logic:
SELECT
EE.IDEstatus, EE.IDAsignacion,EE.IDUNIDAD,
EE.IDEQUIPO,EE.ESTATUS,EE.bUltEstatus,
A.IDDestino, U.UbicacionF, TI.Tiempo
FROM
dbo.mar_EstatusEquipo EE
LEFT JOIN
dbo.mar_Asignaciones A ON EE.IDAsignacion = A.IDAsignacion
AND EE.IDUNIDAD = A.IDUNIDAD
LEFT JOIN
dbo.mar_TmpUbicaciones U ON EE.IDUNIDAD = U.IdUnidad AND U.IdUnidad = A.IDUNIDAD
OUTER APPLY (
SELECT t.Tiempo
FROM
dbo.mar_TiemposArriboPto AS t
INNER JOIN
dbo.Split(U.UbicacionF, ',', '1') AS s ON t.Ubicacion LIKE '%' + s.Value + '%'
) AS TI
WHERE
EE.IDEquipo = CAST(EE.IDUNIDAD AS CHAR)
AND EE.Estatus IN ('IT','ET')
AND A.IDDestino = 'MZO'
AND EE.bUltEstatus = 1
AND EE.IDUNIDAD = 255
ORDER BY
EE.IDUNIDAD
;

Related

GROUP BY with HAVING but unrecognized table in MySQL

I have this query, and I am trying to split the answer column RES (that is divided by commas) into more rows (instead). But when I try to do that, the HAVING part is not working at all, and it's throwing: Unknow column.
This is the original query:
SELECT ad.ID_ANSWER as idRes
, IFNULL(c.NOMBRE_FACTURA,a.INTERVIEWED_NAME) AS nomPdv
, c.CODIGO
, q.`NAME` AS nombreEncuesta
, ad.ID_QUESTION AS idCue
, que.QUESTION
, GROUP_CONCAT(ad.ANSWER) AS RES
, a.LATITUDE
, a.LONGITUDE
, cm.DIRECCION
, c.NIT
, cm.NOMREPRESENTANTE
, cm.FECHA_NACIMIENTO
, a.ID_QUESTIONARY
, cm.TELEFONO, cm.FECHA_NACIMIENTO, cm.NITREPRESENTANTE,
CONCAT(cm.APELLIDO_PATERNO,' ',cm.APELLIDO_MATERNO,' ', cm.NOMBRES_CLIENTE) as RAZONSOCIAL, a.USUARIO_ID, a.FECHA_ID, R.NOMBRE AS RUTA, CASE WHEN D.NOMBRE IS NULL THEN DP.NOMBRE ELSE D.NOMBRE END AS DEPARTAMENTO, P.NOMBRE AS ENCUESTADOR
FROM VM_ANSWER AS a
JOIN VM_ANSWER_DETAIL ad
ON ad.ID_ANSWER = a.ID_ANSWER
JOIN VM_QUESTIONARY AS q
ON q.ID_QUESTIONARY = a.ID_QUESTIONARY
JOIN VM_QUESTION AS que
ON que.ID_QUESTION = ad.ID_QUESTION
JOIN VM_QUESTIONARY_RANGE AS qr
on qr.ID_QUESTIONARY = a.ID_QUESTIONARY
AND qr.OPERACION_ID = 1
JOIN AD_USUARIO U
ON U.USERNAME = a.USUARIO_ID
JOIN GL_PERSONA P
ON P.ID_PERSONA = U.ID_PERSONA
LEFT
JOIN (SELECT * FROM VP_VENDEDOR V GROUP BY V.ID_PERSONA) V ON V.ID_PERSONA = U.ID_PERSONA
LEFT JOIN VP_SUCURSAL S ON S.ID_SUCURSAL = V.ID_SUCURSAL
LEFT JOIN GL_DEPARTAMENTO D ON D.ID_DEPARTAMENTO = S.ID_DEPARTAMENTO
LEFT JOIN VP_CLIENTE AS c ON c.ID_CLIENTE = a.ID_CLIENT
LEFT JOIN VM_CLIENTE_MOVIL AS cm ON cm.ID_CLIENTE = c.ID_CLIENTE
LEFT JOIN GL_DEPARTAMENTO DP ON DP.ID_DEPARTAMENTO = cm.ID_CIUDAD
LEFT JOIN VM_RUTA_VENDEDOR RV ON RV.ID_VENDEDOR = V.ID_VENDEDOR AND RV.OPERACION_ID > 0
LEFT JOIN VM_RUTA R ON R.ID_RUTA = RV.ID_RUTA
WHERE a.OPERACION_ID = 1 AND qr.ID_BRANCH = 3 AND IF (61 = 0, TRUE, a.ID_QUESTIONARY = 61)
GROUP BY a.ID_QUESTIONARY,a.ID_ANSWER
ORDER BY a.ID_QUESTIONARY,a.ID_ANSWER
When I add the following code
LEFT JOIN GL_TIPO T ON T.ID_TIPO = que.ID_TYPE
WHERE a.OPERACION_ID = 1 AND qr.ID_BRANCH = 3 AND IF (61 = 0, TRUE, a.ID_QUESTIONARY = 61)
GROUP BY a.ID_QUESTIONARY,a.ID_ANSWER, ad.ID_ANSWER_DETAIL HAVING T.ID_TIPO=1012
ORDER BY a.ID_QUESTIONARY,a.ID_ANSWER
throws me the error of not recognized table T.ID_TIPO, but if I take off the HAVING word, the left join works normally.
this is the normal result, that as you can see in the column RES, it's divided by a comma when there is more than an answer:
I know it's complicated to understand, 1012 is a multi-select answer type from table GL_TIPO, and it's used in the table Question to define the type of it.
If you can help me to understand what I am doing wrong with the HAVING reserved word it would be awesome, but if you have any suggestion is also welcome too.
Try this:
GROUP BY a.ID_QUESTIONARY,a.ID_ANSWER, que.ID_TIPO=1012
This will put the questions with ID_TIPO=1012 into its own row, and all other ID_TIPO values will be grouped together. Both of these are nested within the ID_QUESTIONARY, ID_ANSWER groups.

Parentheses in mysql query giving different results

I have a query that is giving me different results when i enclosed it in Parentheses, however when I run it without Parentheses its giving me different results. I want to apply Union in between so I have to use Parentheses as without union doesn't work.
The query is as follows:
SELECT Distinct
recurring_billing.id,
recurring_billing.kid_id,
recurring_billing.class_id,
recurring_billing.app_id,
recurring_billing.Region_ID,
CC.month_name,
CC.billing_year,
CASE
WHEN
CC.month_name = recurring_billing.billing_month
AND CC.billing_year = recurring_billing.billing_year
THEN
recurring_billing.billing_status
ELSE
'Pending'
END
AS billing_status, tblkids.kid_name, tblkids.kid_Lastname, tblkids.kid_EMail, tbl_app.app_CCExp AS cc_exp, tbl_app.app_CCName AS cc_name, tbl_app.app_CCNumber AS cc_number, tbl_app.app_CCType AS cc_type, tblclasses.cla_EndDate, tblclassdays.classday_day, CC.remainingclasses, tbl_app.cost_per_class, CC.remainingclasses * tbl_app.cost_per_class AS cost_amount,
CASE
WHEN
OP.override_amt IS NOT NULL
THEN
OP.override_amt
ELSE
CC.remainingclasses * tbl_app.cost_per_class
END
AS pmt_amount,
CASE
WHEN
OP.process_payment = False
THEN
OP.process_payment
ELSE
True
END
AS process_payment
FROM
recurring_billing
LEFT JOIN
tblkidsxclass
ON recurring_billing.kid_id = tblkidsxclass.kxc_kidid
AND recurring_billing.app_id = tblkidsxclass.kxc_appid
LEFT JOIN
tbl_app
ON recurring_billing.app_ID = tbl_app.app_ID
LEFT JOIN
tblkids
ON recurring_billing.kid_id = tblkids.kid_ID
LEFT JOIN
tblclasses
ON recurring_billing.class_id = tblclasses.cla_ID
LEFT JOIN
tblclassdays
ON tblclasses.cla_ID = tblclassdays.classday_classID
INNER JOIN
(
SELECT
MONTHNAME(classday_day) AS month_name,
YEAR(classday_day) AS billing_year,
cla_ID,
COUNT(classday_classid) AS remainingclasses,
c.cost_per_class AS cost_per_class,
COUNT(classday_classid) * cost_per_class AS TotalClassCost
FROM
tblclassdays
JOIN
(
SELECT
tblclasses.cla_ID,
tblclasses.cost_per_class,
tblclasses.cla_nextclass AS next1,
tblclasses_1.cla_nextclass AS next2
FROM
tblclasses
LEFT JOIN
tblclasses AS tblclasses_1
ON tblclasses.cla_nextclass = tblclasses_1.cla_ID
WHERE
tblclasses.cla_ID IN
(
SELECT DISTINCT
recurring_billing.class_id
FROM
recurring_billing
LEFT JOIN
tblkidsxclass
ON recurring_billing.kid_id = tblkidsxclass.kxc_kidid
AND recurring_billing.app_id = tblkidsxclass.kxc_appid -- LEFT JOIN tblkids ON recurring_billing.kid_id = tblkids.kid_ID
LEFT JOIN
tblclasses
ON recurring_billing.class_id = tblclasses.cla_ID -- LEFT JOIN tblclassdays ON tblclasses.cla_ID = tblclassdays.classday_classID
WHERE
ISNULL(tblkidsxclass.kxc_dropoutdate)
AND tblkidsxclass.pmt_option = 'Recurring'
AND tblclasses.cla_active = TRUE -- AND tblclasses.cla_EndDate >= NOW()
GROUP BY
recurring_billing.id
)
)
c
ON tblclassdays.classday_classid IN
(
c.cla_ID,
c.next1,
c.next2
)
WHERE
tblclassdays.classday_noclass = FALSE
AND MONTH(classday_day) = 11
AND YEAR(classday_day) = 2020
AND
(
CONCAT(CAST(classday_day AS DATE), ' ', CAST(classday_endtime AS TIME)) > CAST(CURDATE() AS DATETIME)
)
GROUP BY
cla_ID
)
CC
ON CC.cla_ID = tblclassdays.classday_classID
LEFT JOIN
override_payments OP
ON recurring_billing.app_id = OP.app_id
AND recurring_billing.kid_id = OP.kid_id
AND CC.month_name = OP.billing_month
AND CC.billing_year = OP.billing_year
WHERE
ISNULL(tblkidsxclass.kxc_dropoutdate)
AND tblkidsxclass.pmt_option = 'Recurring'
AND tblclasses.cla_active = TRUE
AND recurring_billing.kid_id NOT IN
(
SELECT
kid_id
from
recurring_billing
where
billing_month = 'November'
and billing_year = '2020'
)
-- AND tblclasses.cla_EndDate >= NOW()
GROUP BY
recurring_billing.id
ORDER BY
recurring_billing.id ASC
Same query if enclosed in Parentheses will give me different results.
Parentheses are not required for a UNION statement. The following 2 union statements both work and yield the same results.
SELECT 1 UNION SELECT 2;
(SELECT 1) UNION (SELECT 2);

Or operator returns more rows then expected mysql

I have a table with some items that are related to car models. Those items could have several categories. I have to select all of them that are related to cars and in all given categories categories for each item stored in sc_products table.
Here is my query:
SELECT
t15_catalogue_line.
T15_GROUP,
sc_products.product_code,
sc_products.unic, sc_products.name_ru, UPPER(TRIM(sc_products.brief_description_ru)) AS brief_description_ru, sc_products.suupplier, price.Price, sc_group_discounts.`action`, sc_group_discounts.procent, sc_products.productID, price.in_stock, price.supplier, t10_item.T10_ITEM, t10_item.unic, t10_item.T10_DESC, t10_item.T10_IMG, t10_item.T10_ITEM_GROUP, t10_item.T10_FIELD1, t10_item.T10_FIELD2, t10_item.T10_FIELD3, t10_item.T10_FIELD4, t10_item.T10_FIELD5, t10_item.T10_FIELD6, t10_item.T10_FIELD7, t10_item.T10_FIELD8, t10_item.T10_FIELD9, t10_item.T10_FIELD10, t10_item.T10_FIELD11, t14_item_fields.T14_ITEM_GROUP, t14_item_fields.T14_FIELD, t14_item_fields.T14_NAME, t14_item_fields.T14_UNIT, t14_item_fields.T14_SEARCH
FROM
sc_products
LEFT OUTER JOIN t15_catalogue_line ON (sc_products.unic = t15_catalogue_line.unic)
LEFT OUTER JOIN price ON (sc_products.unic = price.unic) AND (sc_products.suupplier = price.postavchik)
LEFT OUTER JOIN sc_group_discounts ON (sc_products.item_group = sc_group_discounts.item_group)
LEFT OUTER JOIN t10_item ON (sc_products.unic = t10_item.unic and sc_products.CatText=t10_item.CatText and sc_products.brief_description_ru=t10_item.brand)
LEFT OUTER JOIN t14_item_fields ON (t10_item.T10_ITEM_GROUP = t14_item_fields.T14_ITEM_GROUP)
WHERE
sc_products.CatText = 'bracke mechanism' or
sc_products.CatText='bracke montage ' or
sc_products.CatText='hydraulic repair ' AND
t15_catalogue_line.T15_CARTYPE = '30442' AND
t15_catalogue_line.T15_GROUP = '666' and
sc_products.unic is not null and
sc_products. unic!=''
GROUP BY sc_products.product_code,sc_products.brief_description_ru, sc_products.suupplier
ORDER BY ISNULL( price.price),price.price ASC
Query returns all items in those caegories and they aren't related to auto so table t15_catalog line doesn't take part in query what could be the solution
I highly suspect that the missing parentheses () around the multiple AND is your problem.
Query returns all items in those caegories and they aren't related to auto so table t15_catalog line doesn't take part in query what could be the solution
Your grouping logic now does exactly what you describe, below is what i think you meant to do:
WHERE (sc_products.CatText = 'bracke mechanism' or sc_products.CatText='bracke montage ' or sc_products.CatText='hydraulic repair ') AND t15_catalogue_line.T15_CARTYPE = '30442' AND t15_catalogue_line.T15_GROUP = '666' and sc_products.unic is not null and sc_products. unic!='' GROUP BY sc_products.product_code,sc_products.brief_description_ru, sc_products.suupplier ORDER BY ISNULL( price.price),price.price ASC
This logic:
a OR b OR c AND d is equivalent to a OR b OR (c AND d) and to not (a OR b OR c) AND d which seems to be what you want.
You need to add parentheses around the OR block like this:
WHERE
(
sc_products.CatText = 'bracke mechanism'
OR sc_products.CatText = 'bracke montage '
OR sc_products.CatText = 'hydraulic repair '
)
AND t15_catalogue_line.T15_CARTYPE = '30442'
AND t15_catalogue_line.T15_GROUP = '666'
AND sc_products.unic is not null
AND sc_products. unic!=''
You probably want to use paranthesis in your query for the desired result. How about
SELECT
t15_catalogue_line.
T15_GROUP,
sc_products.product_code,
sc_products.unic, sc_products.name_ru,
UPPER(TRIM (sc_products.brief_description_ru)) AS brief_description_ru,
sc_products.suupplier, price.Price, sc_group_discounts.`action`,
sc_group_discounts.procent, sc_products.productID,
price.in_stock, price.supplier, t10_item.T10_ITEM, t10_item.unic,
t10_item.T10_DESC, t10_item.T10_IMG, t10_item.T10_ITEM_GROUP,
t10_item.T10_FIELD1, t10_item.T10_FIELD2, t10_item.T10_FIELD3,
t10_item.T10_FIELD4, t10_item.T10_FIELD5, t10_item.T10_FIELD6,
t10_item.T10_FIELD7, t10_item.T10_FIELD8, t10_item.T10_FIELD9,
t10_item.T10_FIELD10, t10_item.T10_FIELD11,
t14_item_fields.T14_ITEM_GROUP, t14_item_fields.T14_FIELD,
t14_item_fields.T14_NAME, t14_item_fields.T14_UNIT,
t14_item_fields.T14_SEARCH
FROM
sc_products
LEFT OUTER JOIN t15_catalogue_line ON
(sc_products.unic = t15_catalogue_line.unic)
LEFT OUTER JOIN price ON
(sc_products.unic = price.unic)
AND (sc_products.suupplier = price.postavchik)
LEFT OUTER JOIN sc_group_discounts ON
(sc_products.item_group = sc_group_discounts.item_group)
LEFT OUTER JOIN t10_item ON
(sc_products.unic = t10_item.unic and
sc_products.CatText=t10_item.CatText and
sc_products.brief_description_ru=t10_item.brand)
LEFT OUTER JOIN t14_item_fields ON
(t10_item.T10_ITEM_GROUP = t14_item_fields.T14_ITEM_GROUP)
WHERE
(
sc_products.CatText = 'bracke mechanism'
or
sc_products.CatText='bracke montage '
or
sc_products.CatText='hydraulic repair '
)
AND t15_catalogue_line.T15_CARTYPE = '30442'
AND t15_catalogue_line.T15_GROUP = '666'
and sc_products.unic is not null
and sc_products. unic!=''
GROUP BY
sc_products.product_code,sc_products.brief_description_ru,
sc_products.suupplier ORDER BY ISNULL( price.price),
price.price ASC

How do I join on something else if nothing is found? MySQL

Here is what I have and it does not work. It tries to join on size, if not... it join on if it's equal to '*'
INNER JOIN tbl_items ON (
tbl_items.size = COALESCE(tbl_model.size,'*')
AND tbl_items.type = COALESCE(tbl_model.type,'*')
AND tbl_items.category = COALESCE(tbl_model.category,'*')
AND tbl_items.service = tbl_testTypes.name
)
To join on either the exact column match or an alternative string, you could use a pattern like
(tbl_items.size = tbl_model.size) OR (tbl_model.size = '*')
If it matches, the left side of OR is executed, otherwise the right side is used. Group each inside a ().
So fleshing out your entire JOIN:
INNER JOIN tbl_items ON (
((tbl_items.size = tbl_model.size) OR tbl_model.size = '*')
AND ((tbl_items.type = tbl_model.type) OR tbl_model.type = '*')
AND ((tbl_items.category = tbl_model.category) OR tbl_model.category = '*')
AND (tbl_items.service = tbl_testTypes.name)
)

Converter sql query to Linq

I need to convert this sql query to linq to sql and the result returns a IEnumerable:
select VisualAidName, v.VisualAidID, vs.VisualAidStatusName,
br.BrandName, v.IsEnabled, v.VisualAidCode, v.DateApproved,
br.BrandID, type, UserFirstName+ ' ' + UserLastName as name, AreaID
from VisualAids v inner join VisualAidStatus vs
on v.VisualAidStatusId = vs.VisualAidStatusId
inner join brands br
on v.BrandID = br.BrandId
inner join VisualAids_Areas_Link vareas
on v.VisualAidID = vareas.VisualAidID
left join users us
on v.Owner = us.UserID
where
AreaID IN (
select areaid
from Users inner join Users_Area_Link
on Users.UserID = Users_Area_Link.UserID
where Users.UserID= 3
)
I did this:
IEnumerable<Visual_Aid> visualAll = from v in Context.VisualAids
join vs in Context.VisualAidStatus on v.VisualAidStatusId equals vs.VisualAidStatusId
join br in Context.Brands on v.BrandID equals br.BrandId
join us in Context.Users on v.Owner equals us.UserID into vadis
from x in vadis.DefaultIfEmpty()
select new Visual_Aid()
{
VisualAid_Name = v.VisualAidName,
VisualAid_Id = v.VisualAidID,
VisualAid_StatusName = vs.VisualAidStatusName,
VisualAid_BrandsName = br.BrandName,
VisualAid_IsEnabled = bool.Parse(v.IsEnabled.ToString()),
VisualAid_Code = v.VisualAidCode,
VisualAid_DateApp = v.DateApproved.ToString() ?? "",
VisualAid_BrandId = int.Parse(v.BrandID.ToString()),
VisualAid_Type = v.Type,
VisualAid_Owner = x.UserID == null ? "" : x.UserFirstName + " " + x.UserLastName
};
but I need to do the part of the subquery, ie, I need to include this:
where AreaID IN (
select areaid from Users inner join Users_Area_Link
on Users.UserID = Users_Area_Link.UserID where Users.UserID= 3
)
Anybody know how? thank you very much in advance
You can add this as a where statement:
.......
join us in Context.Users on v.Owner equals us.UserID into vadis
from x in vadis.DefaultIfEmpty()
where (
from user in Context.Users
join userArea in Users_Area_Link
on user.UserID equals userArea.UserID
where user.UserID==3
select userArea.areaid
).Contains(????.AreaID)
select new Visual_Aid()
{
.......