i'm beginner in SQL and i'm trying to calculate a proportion but i don't understand why the code below doesn't work. Can someone help me please ? there is a way to sum(count()) ? thanks for your help.
select
total_piece as Nb_piece,
count(id_vente) as Nb_appartement,
count(id_vente)/sum(Nb_appartement) as "%"
from (
select *
from vente as V
inner join bien as B on V.id_bien = B.id_bien
where type_local = 'Appartement'
) as VB
group by Nb_piece
order by Nb_piece asc
select
total_piece as Nb_piece,
count(id_vente) as Nb_appartement,
count(id_vente)/sum(Nb_appartement) as "%"
from (
select *
from vente as V
inner join bien as B on V.id_bien = B.id_bien
where type_local = 'Appartement'
) as VB
group by total_piece
order by Nb_piece asc
You can't use an alias to group in SQL, use the actual column name to group by
Related
I'm trying to get all the Hikers that traveled in all treks in Nepal.
My tables in the data base are:
Hiker: (hikerID, fullName).
HikerInTrek:(hikerID, trekName).
NepalTreks: (trekName).
I tried the following code:
SELECT fullName
FROM Hiker
WHERE hikerID = (
SELECT hikerID
FROM hikerInTrek
WHERE hikerID not in( SELECT hikerID
FROM ( ( SELECT hikerID, trekName
FROM (SELECT hikerID
FROM hikerInTrek)
cross join
(SELECT trekName
FROM NepalTreks)
)
EXCEPT
( SELECT hikerID, trekName
FROM hikerInTrek
)
)
)
);
I'm working on a website part of a homework and I've wrote this code in the PHP, but I got an error from the "if($queryResult === false) condition after the query. So I guess the query is not correct.
I would use aggregation:
SELECT h.hikerID, h.fullName
FROM Hiker h JOIN
HikerInTrek ht
ON h.hikerID = ht.hikerID JOIN
Nepal_Treks nt
ON nt.TrekName = ht.TrekName
GROUP BY h.hikerID, h.fullName
HAVING COUNT(DISTINCT nt.TrekName) = (SELECT COUNT(*) FROM Nepal_Treks);
Note that this includes hikerID as well. I see no reason to assume that hikers never share the same name.
Depending on how your trekName column is set up, and depending on the SQL dialect it could be something like..
SELECT fullName
FROM Hiker h
JOIN HikerInTrek ht on h.hikerID = ht.hikerID
JOIN Nepal_Treks nt on nt.TrekName = ht.TrekName
Although I'd restructure my tables to have a format like the below (using sql naming conventions)
Hiker
- id
- full_name
HikerTrek
- id
- hiker_id
- trek_id
Trek
- id
- name
- location_id
TrekLocation
- id
- name
Create a row in Hiker for each hiker
Create a row in TrekLocation for Nepal,
Create a row in Trek for each Trek, with location id the one for Nepal
Create a row in HikerTrek for each trek a hiker has been on,
Then you can query it like this
SELECT h.full_name
FROM Hiker h
JOIN HikerTrek ht on h.id = ht.hiker_id
JOIN Trek t on ht.trek_id = t.id
JOIN TrekLocation tl on t.location_id = tl.id
WHERE tl.name = "Nepal"
Hope this clears things up a little.
Try this.
SELECT
A.fullName
FROM
Hiker A
INNER JOIN
HikerInTrek B ON B.hikerID = A.hikerID
WHERE
B.trekName = 'Nepal'
I have a table I called Eventos. I have to select the corresponding outTime from the alarm which has the greater inTime.
And I have to do it quickly/optimized. I have about 1 million entries in the table.
This is my code:
SELECT
CadGrupoEventos.Severidade AS Nível,
CadGrupoEquipamentos.Nome AS Grupo,
CadEquipamentos.TAG AS Equipamento,
CadEventos.MensagemPT AS 'Mensagem de alarme',
MAX(Eventos.InTime) AS 'Hora do evento',
Eventos.OutTime AS 'Hora de saída'
FROM
CadGrupoEventos,
CadEquipamentos,
CadEventos,
Eventos,
CadUsuarios,
CadGrupoEquipamentos
WHERE
Eventos.Acked = 0
AND CadGrupoEventos.Codigo = CadEventos.Grupo
AND CadEquipamentos.Codigo = Eventos.TAG
AND CadEventos.Codigo = Eventos.CodMensagem
AND CadGrupoEquipamentos.Codigo = CadEquipamentos.Grupo
GROUP BY
CadGrupoEventos.Severidade,
CadEquipamentos.TAG,
CadEventos.MensagemPT,
CadGrupoEquipamentos.Nome,
Eventos.OutTime
This code, as it is, returns every single entry from the table.
I have to take Eventos.OutTime out of GROUP BY and still get the value of it.
This is just an educated guess based on your description. Notice I used ANSI-92 style joins which are much more explicit. I also used aliases to make this a lot more legible. Your query might look something like this.
select x.Severidade AS Nível,
x.Nome AS Grupo,
x.TAG AS Equipamento,
x.MensagemPT AS [Mensagem de alarme],
x.[Hora do evento],
x.OutTime AS [Hora de saída]
from
(
SELECT cge.Severidade,
cgequip.Nome,
ce.TAG,
cevt.MensagemPT,
MAX(e.InTime) AS [Hora do evento],
e.OutTime
, RowNum = ROW_NUMBER() over(partition by cge.Severidade, ce.TAG, cevt.MensagemPT, cgequip.Nome order by e.OutTime /*maybe desc???*/)
FROM CadGrupoEventos cge
join CadEventos cevt on cge.Codigo = cevt.Grupo
join Eventos e on AND cevt.Codigo = e.CodMensagem
join CadEquipamentos ce on ce.Codigo = e.TAG
join CadGrupoEquipamentos cgequip on cgequip.Codigo = ce.Grupo
cross join CadUsuarios cu --not sure if this is really what you want but your original code did not have any logic for this table
WHERE e.Acked = 0
GROUP BY cge.Severidade,
ce.TAG,
cevt.MensagemPT,
cgequip.Nome,
e.OutTime
) x
where x.RowNum = 1
Here's my code:
SELECT B1_COD, SB1030.B1_DESC, B2_CM1, B2_QATU, SUM (B2_QATU)
FROM SB1030
INNER JOIN SB2030 ON B1_COD = B2_COD
WHERE (B1_TIPO='PA') AND (B2_QATU <> '0')
I'd like to:
multiply b2_cm1 by b2_qatu creating b2_VAL
sum all b2_qatu with same b1_cod creating b2_SAL
divide b2_VAL by b2_SAL
Could anyone help me?????
Thanks
Here is what I think you are looking for. A list of b1_cods with sums and a calculation based on the sums.
select
b1_cod,
sb1030.b1_desc,
sum(b2_cm1) as sum_cm1,
sum(b2_qatu) as b2_sal,
sum(b2_qatu * b2_cm1) as b2_val,
sum(b2_qatu) / sum(b2_qatu * b2_cm1) as new_field
from sb1030
inner join sb2030 on b1_cod = b2_cod
where b1_tipo = 'pa' and b2_qatu <> '0'
group by b1_cod, sb1030.b1_desc
order by b1_cod, sb1030.b1_desc;
Do you only want the result b2_VAL and b2_SAL?
Try using WITH CTE:
WITH CTE AS(
SELECT SUM(B1_COD) AS B1_COD, SB1030.B1_DESC,B2_CM1*B2_QATU AS b2_VAL, SUM (B2_QATU) AS B2_QATU
FROM SB1030
INNER JOIN SB2030 ON B1_COD = B2_COD
WHERE (B1_TIPO='PA') AND (B2_QATU <> '0'))
SELECT B1_COD+B2_QATU, b2_VAL
FROM CTE
Is it something like that you are looking for?
Ok here's my View (vw_LiftEquip)
SELECT dbo.tbl_equip_swl_unit.unit_id,
dbo.tbl_equip_swl_unit.unit_name,
dbo.tbl_equip_swl_unit.archived,
dbo.tbl_categories.category_id,
dbo.tbl_categories.categoryName,
dbo.tbl_categories.parentCategory,
dbo.tbl_categories.sub_category,
dbo.tbl_categories.desc_category,
dbo.tbl_categories.description,
dbo.tbl_categories.miscellaneous,
dbo.tbl_categories.category_archived,
dbo.tbl_equip_swl_unit.unit_name AS Expr1,
dbo.tbl_categories.categoryName AS Expr2,
dbo.tbl_categories.description AS Expr3,
dbo.tbl_equip_depts.dept_name,
dbo.tbl_equip_man.man_name,
dbo.tbl_Lifting_Gear.e_defects AS Expr7,
dbo.tbl_Lifting_Gear.e_defects_desc AS Expr8,
dbo.tbl_Lifting_Gear.e_defects_date AS Expr9,
dbo.tbl_equipment.equipment_id,
dbo.tbl_equipment.e_contract_no,
dbo.tbl_equipment.slID,
dbo.tbl_equipment.e_entered_by,
dbo.tbl_equipment.e_serial,
dbo.tbl_equipment.e_model,
dbo.tbl_equipment.e_description,
dbo.tbl_equipment.e_location_id,
dbo.tbl_equipment.e_owner_id,
dbo.tbl_equipment.e_department_id,
dbo.tbl_equipment.e_manafacture_id,
dbo.tbl_equipment.e_manDate1,
dbo.tbl_equipment.e_manDate2,
dbo.tbl_equipment.e_manDate3,
dbo.tbl_equipment.e_dimensions,
dbo.tbl_equipment.e_test_no,
dbo.tbl_equipment.e_firstDate1,
dbo.tbl_equipment.e_firstDate2,
dbo.tbl_equipment.e_firstDate3,
dbo.tbl_equipment.e_prevDate1,
dbo.tbl_equipment.e_prevDate2,
dbo.tbl_equipment.e_prevDate3,
dbo.tbl_equipment.e_insp_frequency,
dbo.tbl_equipment.e_swl,
dbo.tbl_equipment.e_swl_unit_id,
dbo.tbl_equipment.e_swl_notes,
dbo.tbl_equipment.e_cat_id,
dbo.tbl_equipment.e_sub_id,
dbo.tbl_equipment.e_parent_id,
dbo.tbl_equipment.e_last_inspector,
dbo.tbl_equipment.e_last_company,
dbo.tbl_equipment.e_deleted AS Expr11,
dbo.tbl_equipment.e_deleted_desc AS Expr12,
dbo.tbl_equipment.e_deleted_date AS Expr13,
dbo.tbl_equipment.e_deleted_insp AS Expr14,
dbo.tbl_Lifting_Gear.e_defects_action AS Expr15,
dbo.tbl_equipment.e_rig_location,
dbo.tbl_Lifting_Gear.e_add_type AS Expr17,
dbo.tbl_Lifting_Gear.con_id,
dbo.tbl_Lifting_Gear.lifting_date,
dbo.tbl_Lifting_Gear.lifting_ref_no,
dbo.tbl_Lifting_Gear.e_id,
dbo.tbl_Lifting_Gear.inspector_id,
dbo.tbl_Lifting_Gear.lift_testCert,
dbo.tbl_Lifting_Gear.lift_rig_location,
dbo.tbl_Lifting_Gear.inspected,
dbo.tbl_Lifting_Gear.lifting_through,
dbo.tbl_Lifting_Gear.liftingNDT,
dbo.tbl_Lifting_Gear.liftingTest,
dbo.tbl_Lifting_Gear.e_defects,
dbo.tbl_Lifting_Gear.e_defects_desc,
dbo.tbl_Lifting_Gear.e_defects_date,
dbo.tbl_Lifting_Gear.e_defects_action,
dbo.tbl_Lifting_Gear.lift_department_id,
dbo.tbl_Lifting_Gear.lifting_loc
FROM dbo.tbl_equipment
INNER JOIN dbo.tbl_equip_swl_unit
ON dbo.tbl_equipment.e_swl_unit_id = dbo.tbl_equip_swl_unit.unit_id
INNER JOIN dbo.tbl_categories
ON dbo.tbl_equipment.e_cat_id = dbo.tbl_categories.category_id
INNER JOIN dbo.tbl_equip_depts
ON dbo.tbl_equipment.e_department_id = dbo.tbl_equip_depts.dept_id
INNER JOIN dbo.tbl_equip_man
ON dbo.tbl_equipment.e_manafacture_id = dbo.tbl_equip_man.man_id
INNER JOIN dbo.vwSubCategory
ON dbo.tbl_equipment.e_sub_id = dbo.vwSubCategory.category_id
INNER JOIN dbo.vwDescCategory
ON dbo.tbl_equipment.e_cat_id = dbo.vwDescCategory.category_id
INNER JOIN dbo.tbl_Lifting_Gear
ON dbo.tbl_equipment.equipment_id = dbo.tbl_Lifting_Gear.e_id
And here's the select statement with subquery that I am using:
SELECT *
FROM vw_LiftEquip
WHERE lifting_loc = ? AND
con_id = ? AND
EXPR11 =
'N'(
SELECT MAX(lifting_date) AS maxLift
FROM vw_LiftEquip
WHERE e_id = equipment_id
)
ORDER BY lifting_ref_no,
category_id,
e_swl,
e_serial
I get the error :
Column "vw_LiftEquip.category_id" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
Can't see why its returning that error, this is admittedly the first time I've ran a subquery on such a complex view, and I am a bit lost, thanks in advance for any help. I have looked through the similar posts and can find no answers to this one, sorry if I am just being dumb.
You are missing AND between EXPR11 = 'N' and (SELECT MAX(...
Otherwise, it looks OK. MAX without GROUP BY is allowed if you have no other columns in the SELECT
Update: #hvd also noted that you have nothing to compare to MAX(lifting_date). See comment
Update 2,
SELECT *
FROM vw_LiftEquip v1
CROSS JOIN
(
SELECT MAX(lifting_date) AS maxLift
FROM vw_LiftEquip
WHERE e_id = equipment_id
) v2
WHERE v1.lifting_loc = ? AND
v1.con_id = ? AND
v1.EXPR11 = 'N'
ORDER BY v1.lifting_ref_no,
v1.category_id,
v1.e_swl,
v1.e_serial
I have a query:
SELECT A.AHSHMT AS SHIPMENT, A.AHVNAM AS VENDOR_NAME, D.UNITS_SHIPPED, D.ADPON AS PO, B.NUMBER_OF_CASES_ON_TRANSIT, C.NUMBER_OF_CASES_RECEIVED FROM AHASNF00 A
INNER JOIN (SELECT IDSHMT, COUNT(*) AS NUMBER_OF_CASES_ON_TRANSIT FROM IDCASE00 WHERE IDSTAT = '01' GROUP BY IDSHMT) B
ON (A.AHSHMT = B.IDSHMT)
LEFT JOIN (SELECT IDSHMT, (COUNT(*) AS NUMBER_OF_CASES_RECEIVED FROM IDCASE00 WHERE IDSTAT = '10' GROUP BY IDSHMT) C
ON (A.AHSHMT = C.IDSHMT)
INNER JOIN (SELECT ADSHMT, ADPON, SUM(ADUNSH) AS UNITS_SHIPPED FROM ADASNF00 GROUP BY ADSHMT, ADPON) D
ON (A.AHSHMT = D.ADSHMT)
WHERE A.AHSHMT = '540041134';
On the first JOIN statement I have a COUNT(*), on this count sometimes I will get NULL. I need to replace this with a "0-zero", I know think I know how to do it in SQL
ISNULL(COUNT(*), 0)
But this doesn't work for DB2, how can I accomplish this? All your help is really appreciate it.
Wrap a COALESCE around each of the nullable totals in your SELECT list:
SELECT A.AHSHMT AS SHIPMENT,
A.AHVNAM AS VENDOR_NAME,
COALESCE( D.UNITS_SHIPPED, 0 ) AS UNITS_SHIPPED,
D.ADPON AS PO,
COALESCE( B.NUMBER_OF_CASES_ON_TRANSIT, 0 ) AS NUMBER_OF_CASES_ON_TRANSIT,
COALESCE( C.NUMBER_OF_CASES_RECEIVED, 0 ) AS NUMBER_OF_CASES_RECEIVED
FROM ...
The inner joins you're using for expressions B and D mean that you will only receive rows from A that have one or more cases in transit (expression B) and have one or more POs in expression D. Is that the way you want your query to work?
Instead of using ISNULL(COUNT(*), 0),
try using COALESCE(COUNT(*),0)
use IFNULL(COUNT(*), 0) for DB2