How to update this Select Query to Update? - So far, it just hangs - sql

I eventually managed to get what I was after by grouping and then applying an additional filter with 'HAVING' which is probably not the best way to go about it, but I am new to SQL and this is the only way I could achieve what I was after... which was a list of 'simple' items where the 'qty' is 0 and the range status (attribute_id = 168) is Discontinued (ID 96) and the 'status' (attribute_id = 97) is enabled (id = 1). This is shown below:
SELECT
`mgic_catalog_product_entity`.`sku` AS `sku`,
`mgic_catalog_product_entity`.`type_id` AS `type_id`,
`mgic_cataloginventory_stock_item`.`qty` AS `qty`,
MAX(Case WHEN `mgic_eav_attribute`.`attribute_id` = 97 THEN `mgic_catalog_product_entity_int`.`value` END) AS status,
MAX(Case WHEN `mgic_eav_attribute`.`attribute_id` = 168 THEN `mgic_catalog_product_entity_int`.`value` END) AS range_status
FROM (((`mgic_eav_attribute`
join `mgic_catalog_product_entity_int` on ((`mgic_eav_attribute`.`attribute_id` = `mgic_catalog_product_entity_int`.`attribute_id`)))
join `mgic_catalog_product_entity` on ((`mgic_catalog_product_entity_int`.`entity_id` = `mgic_catalog_product_entity`.`entity_id`)))
join `mgic_cataloginventory_stock_item` on ((`mgic_catalog_product_entity_int`.`entity_id` = `mgic_cataloginventory_stock_item`.`product_id`)))
WHERE `mgic_catalog_product_entity`.`type_id` = 'simple' AND `mgic_cataloginventory_stock_item`.`qty` = 0
GROUP BY `mgic_catalog_product_entity`.`sku`
HAVING status = 1 and range_status = 96;
I am now trying to amend this to an update instruction to set the 'status' (attribute_id = 97) to disabled (id = 2) for the results list of the below query.
update mgic_eav_attribute ea join
mgic_catalog_product_entity_int cpei on ea.attribute_id = cpei.attribute_id join
mgic_catalog_product_entity cpe on cpei.entity_id = cpe.entity_id join
mgic_cataloginventory_stock_item cisi on cpei.entity_id = cisi.product_id
set cpei.value = 2
WHERE cpe.type_id = 'simple' AND ((ea.attribute_code = 'status') and
(cpei.value = 1)) AND cisi.qty = 0 AND EXISTS(
SELECT
cpe.sku,
cpe.type_id,
cisi.qty,
MAX(Case WHEN ea.attribute_id = 97 THEN cpei.value END) AS status,
MAX(Case WHEN ea.attribute_id = 168 THEN cpei.value END) AS range_status
FROM (((`mgic_eav_attribute`
join `mgic_catalog_product_entity_int` on ((`mgic_eav_attribute`.`attribute_id` = `mgic_catalog_product_entity_int`.`attribute_id`)))
join `mgic_catalog_product_entity` on ((`mgic_catalog_product_entity_int`.`entity_id` = `mgic_catalog_product_entity`.`entity_id`)))
join `mgic_cataloginventory_stock_item` on ((`mgic_catalog_product_entity_int`.`entity_id` = `mgic_cataloginventory_stock_item`.`product_id`)))
WHERE `mgic_catalog_product_entity`.`type_id` = 'simple' AND `mgic_cataloginventory_stock_item`.`qty` = 0
GROUP BY cpei.entity_id
HAVING status = 1 and range_status = 96);
The above query just seems to hang and doesn't execute. Can anyone help?

Related

How resolve a error that a subquery is not introduced with EXISTS?

I am trying to run my query but I get an error.
This is my query:
SELECT DISTINCT
F.FORN_ID,
F.FORN_COD,
F.FORN_DESC,
FORN_CEP,
FORN_CNPJ,
F.PAIS_COD,
F.REGI_COD,
(SELECT TOP 1 CONT_NOME FROM CONT_CONTATOS WHERE CONT_PRINCIPAL = 1 AND SEGM_COD = #SEGM_COD AND CONT_INATIVO = 0 AND FORN_ID IN(SELECT FORN_ID FROM FORN_FORNECEDORES WHERE MSTR_ID = F.FORN_ID)) AS CONT_NOME,
(SELECT TOP 1 CONT_EMAIL FROM CONT_CONTATOS WHERE CONT_PRINCIPAL = 1 AND SEGM_COD = #SEGM_COD AND CONT_INATIVO = 0 AND FORN_ID IN(SELECT FORN_ID FROM FORN_FORNECEDORES WHERE MSTR_ID = F.FORN_ID)) AS CONT_EMAIL,
(SELECT TOP 1 SEGM_COD FROM CONT_CONTATOS WHERE CONT_PRINCIPAL = 1 AND SEGM_COD = #SEGM_COD AND CONT_INATIVO = 0 AND FORN_ID IN(SELECT FORN_ID FROM FORN_FORNECEDORES WHERE MSTR_ID = F.FORN_ID)) AS SEGM_COD,
(SELECT FORN.* FROM FORNECEDORES_PERFIL as FORN
LEFT JOIN PERF_PERFIL as PERFIL
ON FORN.PERF_COD = PERFIL.PERF_COD
LEFT JOIN FAB_FABRICA as FAB ON FORN.FAB_COD = FAB.FAB_COD
LEFT JOIN TIPO_FABRICAS as TIPO_FAB ON FORN.TP_FAB_COD = TIPO_FAB.TP_FAB_COD
WHERE FORN_ID = F.FORN_ID
) AS PROFILE,
--C.CONT_NOME,
--C.CONT_TEL,
--C.CONT_TEL2,
--C.CONT_CEL,
--C.CONT_EMAIL,
--C.SEGM_COD,
F.FEIR_COD,
FE.FEIR_DESC,
F.CREATE_DATE,
F.FORN_STATUS,
F.USU_COD,
(SELECT COUNT(CONT_ID) FROM CONT_CONTATOS WHERE CONT_PRINCIPAL = 1 AND SEGM_COD = #SEGM_COD AND CONT_INATIVO = 0 AND FORN_ID IN(SELECT FORN_ID FROM FORN_FORNECEDORES WHERE MSTR_ID = FORN_ID)) AS COUNT_CONT_PRINCIPAL,
F.PLAT_ID,
F.MSTR_ID,
F.CODE,
(SELECT SEGM_COD FROM FORNECEDORES_FAVORITOS WHERE SEGM_COD = #SEGM_COD AND FORN_ID = F.FORN_ID) AS FAVORITES,
(SELECT COUNT(NOTA_ID) FROM NOTA_NOTAS WHERE SEGM_COD = #SEGM_COD AND TP_NOTA_ID = 2 AND NOTA_INATIVA = 0 AND OBJ_ID = F.FORN_ID) AS NOTA_COUNT,
ROW_NUMBER() OVER(ORDER BY F.FORN_ID) AS LINHA,
F.UPDATE_DATE
FROM FORN_FORNECEDORES F
LEFT OUTER JOIN FEIR_FEIRAS FE (nolock) ON FE.FEIR_COD = F.FEIR_COD
--LEFT OUTER JOIN END_ENDERECOS E ON E.FORN_ID = F.FORN_ID
--LEFT OUTER JOIN CONT_CONTATOS C ON C.FORN_ID = F.FORN_ID AND C.CONT_PRINCIPAL = 1 AND C.CONT_INATIVO = 0
WHERE (F.FORN_DESC like '%'+#FORN_DESC+'%' or #FORN_DESC IS NULL)
AND (F.FEIR_COD = #FEIR_COD or #FEIR_COD IS NULL)
AND (F.FORN_ID = #FORN_ID or #FORN_ID IS NULL)
AND (F.FORN_STATUS = #FORN_STATUS or #FORN_STATUS IS NULL)
AND (F.USU_COD = #USUARIO_ID OR #USUARIO_ID IS NULL)
AND (CONVERT(VARCHAR(10),F.CREATE_DATE,102) >= CONVERT(VARCHAR(10),#CREATE_DATE_I,102)or #CREATE_DATE_I IS NULL)
AND (CONVERT(VARCHAR(10),F.CREATE_DATE,102) <= CONVERT(VARCHAR(10),#CREATE_DATE_F,102) or #CREATE_DATE_F IS NULL)
AND (CONVERT(VARCHAR(10),F.UPDATE_DATE,102) >= CONVERT(VARCHAR(10),#UPDATE_DATE,102)or #UPDATE_DATE IS NULL)
AND FORN_INATIVO = 0
AND F.FORN_ID = F.MSTR_ID
`
the error is exactly when I added this sub query
(SELECT FORN.* FROM FORNECEDORES_PERFIL as FORN
LEFT JOIN PERF_PERFIL as PERFIL
ON FORN.PERF_COD = PERFIL.PERF_COD
LEFT JOIN FAB_FABRICA as FAB ON FORN.FAB_COD = FAB.FAB_COD
LEFT JOIN TIPO_FABRICAS as TIPO_FAB ON FORN.TP_FAB_COD = TIPO_FAB.TP_FAB_COD
WHERE FORN_ID = F.FORN_ID
) AS PROFILE,
I observed some random questions but none of them worked, I even tried to add FORN.* but without success
This error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
It's this subquery in the SELECT clause:
(SELECT FORN.* FROM FORNECEDORES_PERFIL as FORN
LEFT JOIN PERF_PERFIL as PERFIL
ON FORN.PERF_COD = PERFIL.PERF_COD
LEFT JOIN FAB_FABRICA as FAB ON FORN.FAB_COD = FAB.FAB_COD
LEFT JOIN TIPO_FABRICAS as TIPO_FAB ON FORN.TP_FAB_COD = TIPO_FAB.TP_FAB_COD
WHERE FORN_ID = F.FORN_ID
) AS PROFILE,
Each item in the SELECT clause is only allowed to have ONE value. However, the subquery returns FORN.*, which is many values. If you really want to include every column from the subquery in the results, you may try using an APPLY lateral join instead.

How to select twice the same column on join query?

How Can I to count the gender when is M or F, somehting like
SELECT count(N.gender)
FROM `DATABASE_T` as T
LEFT JOIN `DATABASE_N` as N
ON
T.ENCUESTA = N.ENCUESTA AND
T.P_DEPTO = N.P_DEPTO AND
T.P_MUNIC = N.P_MUNIC AND
T.COD_VEREDA = N.COD_VEREDA AND
T.PAIS = N.PAIS and
T.UC_UO = N.UC_UO
WHERE N.ID_PROD=1 and N.gender="M"
SELECT countif(N.gender = 'M') as M, countif(N.gender = 'F') as F
FROM `DATABASE_T` as T
LEFT JOIN `DATABASE_N` as N
ON
T.ENCUESTA = N.ENCUESTA AND
T.P_DEPTO = N.P_DEPTO AND
T.P_MUNIC = N.P_MUNIC AND
T.COD_VEREDA = N.COD_VEREDA AND
T.PAIS = N.PAIS and
T.UC_UO = N.UC_UO
WHERE N.ID_PROD=1
Since you did not describe the structure of your table and use Spanish-looking identifiers, I will use a clearer example with my own schema:
SELECT
SUM( CASE WHEN Sex = 'M' THEN 1 ELSE 0 END ) AS M,
SUM( CASE WHEN Sex = 'F' THEN 1 ELSE 0 END ) AS F
FROM People
WHERE People.Dept = 5

Select rows from related table which matches different conditions

I have a table called places which looks like this:
and another table called place_addons_saved which looks like this:
How can I write a query that relates place_addons_saved.place and places.id and searches rows that matches ONLY places which have all the conditions?
For example when I'll search for rows that have place_addon = 163, place_option = 329 and place_addon = 162, place_option = 324 will return place with id of a 80, but when I'll search for rows that have place_addon = 162, place_option = 326 and place_addon = 163, place_option = 330 the query must return nothing, because place 80 doesn't fit the 2nd condition
If I understand correctly, you can use group by and having:
select place
from place_addons_saved
where (place_addon = 163 and place_option = 329) or
(place_addon = 162 and place_option = 324)
group by place
having count(*) = 2; -- "2" is the number of comparisons
To get all the information about the places:
select p.*
from places p
where p.id in (select place
from place_addons_saved
where (place_addon = 163 and place_option = 329) or
(place_addon = 162 and place_option = 324)
group by place
having count(*) = 2; -- "2" is the number of comparisons
);
This could work:
With GetResult (place,chk1,chk2) As
(
SELECT
pas.place,
sum(Case When (pas.place_addon = 163) AND (pas.place_option = 329) then 1 Else 0 End) As chk1,
sum(Case When (pas.place_addon = 162) AND (pas.place_option = 324) then 1 Else 0 End) As chk2
FROM
places AS p RIGHT OUTER JOIN
place_addons_saved AS pas ON p.id = pas.place
group by pas.place
)
Select * From GetResult Where chk1 > 0 and chk2 > 0

Calculating (dividing) two summed fields in SQL Query

I have this query:
Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage
from [AI_DataMart].[AzureViews].[v_FactMeteredUsageMonthly] as FMUM
join [AI_DataMart].[AzureViews].[v_DimServiceExtended] as SE on(FMUM.DimServiceKey = SE.DimServiceKey)
join [AI_DataMart].[AzureViews].[v_DimAccount] as A on(FMUM.DimAccountKey = A.DimAccountKey)
Join [AI_DataMart].[AzureViews].[v_DimSubscription] as SU on(FMUM.DimSubscriptionKey = SU.DimSubscriptionKey)
where
FMUM.DimDateKey >= '20150201'And FMUM.DimDateKey <= '20150331'
And SE.Workload = 'SQLDB'
And SE.ResourceName != 'SQL Reporting Hours'
And (SU.AI_BillingType = 'EA' or SU.AI_BillingType = 'Direct')
AND SU.IsFraudIdentified = 0
AND SU.AI_IsTest = 0
AND SU.DimBillingSystemKey = 1
AND FMUM.DimSubscriptionKey = '4707785'
group by FMUM.DimSubscriptionKey
Which Returns this result:
DimSubscriptionKey TotalUnits AI_NormalizedUsage
4707785 24.77043700 21.08775630
What I need to get and can't get to work is a 4th Column Which would be (AI_NormaliedUsage / TotalUnits)
But when I add it to the query:
Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage, (AI_NormalizedUsage / TotalUnits)
from [AI_DataMart].[AzureViews].[v_FactMeteredUsageMonthly] as FMUM
join [AI_DataMart].[AzureViews].[v_DimServiceExtended] as SE on(FMUM.DimServiceKey = SE.DimServiceKey)
join [AI_DataMart].[AzureViews].[v_DimAccount] as A on(FMUM.DimAccountKey = A.DimAccountKey)
Join [AI_DataMart].[AzureViews].[v_DimSubscription] as SU on(FMUM.DimSubscriptionKey = SU.DimSubscriptionKey)
where
FMUM.DimDateKey >= '20150201'And FMUM.DimDateKey <= '20150331'
And SE.Workload = 'SQLDB'
And SE.ResourceName != 'SQL Reporting Hours'
And (SU.AI_BillingType = 'EA' or SU.AI_BillingType = 'Direct')
AND SU.IsFraudIdentified = 0
AND SU.AI_IsTest = 0
AND SU.DimBillingSystemKey = 1
AND FMUM.DimSubscriptionKey = '4707785'
group by FMUM.DimSubscriptionKey, (AI_NormalizedUsage / TotalUnits)
I am not getting expected results:
DimSubscriptionKey TotalUnits AI_NormalizedUsage (No column name)
4707785 1.45831000 0.70567620 0.48389999382847268413
4707785 3.39577900 3.28609533 0.96769999755578911348
4707785 9.49984800 9.19300290 0.96769999898945751553
4707785 3.41661200 3.30625543 0.96769999929754973640
4707785 4.49992800 2.17751515 0.48389999795552284392
4707785 2.49996000 2.41921129 0.96769999919998719979
What I want is
DimSubscriptionKey TotalUnits AI_NormalizedUsge NewCalculatedField<br>
4707785 24.770437 21.0877563 0.851327585
What am I missing? Racking my brain!
if you're referencing derived columns from within the same select statement you can't refer to them by their alias, you need to either duplicate the calculation, or wrap it in another select statement.
Without knowing anything about the underlying tables, this fix should work:
Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage, sum(FMUM.AI_NormalizedUsage) / sum(FMUM.TotalUnits) NewCalculatedField
from [AI_DataMart].[AzureViews].[v_FactMeteredUsageMonthly] as FMUM
join [AI_DataMart].[AzureViews].[v_DimServiceExtended] as SE on(FMUM.DimServiceKey = SE.DimServiceKey)
join [AI_DataMart].[AzureViews].[v_DimAccount] as A on(FMUM.DimAccountKey = A.DimAccountKey)
Join [AI_DataMart].[AzureViews].[v_DimSubscription] as SU on(FMUM.DimSubscriptionKey = SU.DimSubscriptionKey)
where
FMUM.DimDateKey >= '20150201'And FMUM.DimDateKey <= '20150331'
And SE.Workload = 'SQLDB'
And SE.ResourceName != 'SQL Reporting Hours'
And (SU.AI_BillingType = 'EA' or SU.AI_BillingType = 'Direct')
AND SU.IsFraudIdentified = 0
AND SU.AI_IsTest = 0
AND SU.DimBillingSystemKey = 1
AND FMUM.DimSubscriptionKey = '4707785'
group by FMUM.DimSubscriptionKey
Sorry I can't comment but have you tried this:
Select FMUM.DimSubscriptionKey, sum(FMUM.TotalUnits) as TotalUnits, sum(FMUM.AI_NormalizedUsage) as AI_NormalizedUsage, (sum(FMUM.AI_NormalizedUsage / sum(FMUM.TotalUnits))
Should not need the group by either.

sql: where subquery not null

I have the following sql query and I want to filter the results where the alias imagefile is null, but I can't get it to work. it's kinda basic sql... sorry for that!
SELECT Categorie.CategorieID, Categorie.Highlight, CategorieTaal.CategorieNaam,
(SELECT TOP (1) ImageFile
FROM Artikel WHERE (CategorieID = Categorie.CategorieID)
AND (Onzichtbaar = 0)
AND (NietBestelbaar = 0)
AND (Voorraad = - 1000 OR Voorraad > LevertijdDrempel)
ORDER BY Volgnummer, ArtikelID DESC) AS 'imagefile'
FROM Categorie INNER JOIN
CategorieTaal ON
Categorie.CategorieID = CategorieTaal.CategorieID
WHERE (Categorie.CategorieGroepID = #catgroepid)
AND (Categorie.Onzichtbaar = 0)
AND (CategorieTaal.TaalCode = #tc)
ORDER BY Categorie.Volgnummer, CategorieTaal.CategorieNaam
You might want to try this:
SELECT Categorie.CategorieID, Categorie.Highlight, CategorieTaal.CategorieNaam,
FROM Categorie
INNER JOIN
CategorieTaal ON
Categorie.CategorieID = CategorieTaal.CategorieID
WHERE (Categorie.CategorieGroepID = #catgroepid)
AND (Categorie.Onzichtbaar = 0)
AND (CategorieTaal.TaalCode = #tc)
AND NOT EXISTS (SELECT 1 ImageFile
FROM Artikel WHERE (CategorieID = Categorie.CategorieID)
AND (Onzichtbaar = 0)
AND (NietBestelbaar = 0)
AND (Voorraad = - 1000 OR Voorraad > LevertijdDrempel))
ORDER BY Categorie.Volgnummer, CategorieTaal.CategorieNaam
You can optimize this by using an inner join again, in lieu of trying to use a subquery twice:
SELECT
c.CategorieID,
c.Highlight,
ct.CategorieNaam,
a.ImageFile
FROM
Categorie c
INNER JOIN CategorieTaal ct ON
c.CategorieID = ct.CategorieID
INNER JOIN
(select
CategorieID,
ImageFile,
row_number() over (partition by CategorieID) as rownum
from
Artikel
where
Onzichtbaar = 0
and NietBestelbaar = 0
and (Voorraad = -1000 OR Voorraad > LevertijdDrempel)) a ON
c.CategorieID = a.CategorieID
and a.rownum = 1
WHERE
c.CategorieGroepID = #catgroepid
AND c.Onzichtbaar = 0
AND ct.TaalCode = #tc
ORDER BY c.Volgnummer, ct.CategorieNaam
Since you're using SQL Server (or at least I think you are, with your top and whatnot), you can take advantage of row_number. This will bring back just the ImageFile you need, without having to do two correlated subqueries (usually performance killers).
Also, here you only have to maintain that subquery in one place, not in two different parts of your query.
found it!!
SELECT Categorie.CategorieID, Categorie.Highlight, CategorieTaal.CategorieNaam,
(SELECT TOP (1) ImageFile
FROM Artikel
WHERE (CategorieID = Categorie.CategorieID)
AND (Onzichtbaar = 0)
AND (NietBestelbaar = 0)
AND (Voorraad = - 1000
OR Voorraad > LevertijdDrempel)
ORDER BY Volgnummer, ArtikelID DESC) AS 'imagefile'
FROM Categorie
INNER JOIN CategorieTaal ON Categorie.CategorieID = CategorieTaal.CategorieID
WHERE (Categorie.CategorieGroepID = #catgroepid)
AND (Categorie.Onzichtbaar = 0)
AND (CategorieTaal.TaalCode = #tc)
AND ((
SELECT TOP (1) ImageFile
FROM Artikel AS Artikel_1
WHERE (CategorieID = Categorie.CategorieID)
AND (Onzichtbaar = 0)
AND (NietBestelbaar = 0)
AND (Voorraad = - 1000
OR Voorraad > LevertijdDrempel)
) IS NOT NULL)
ORDER BY Categorie.Volgnummer, CategorieTaal.CategorieNaam