2

Hello I'm using two tables to have one query. I have municipality and barangay and household_connector_id fields in household_tbl but in second table which is tbl_household_member is only have a household_connector_id field. the alias for the first select to use on the subquery is not working. Please help.

Here is the query:

SELECT household_connector_id as h_id,
       barangay as b,
       municipality as m,

(SELECT COUNT(*) FROM household_tbl WHERE municipality = m
AND SUBSTR(expiry_date,1,2) LIKE "04" AND SUBSTR(expiry_date,7,4) LIKE "2013" AND NOT(expiry_date = "") AND NOT(expiry_date = "n/a"))   
+

(SELECT COUNT(*) FROM tbl_household_members WHERE household_connector_id = h_id
AND SUBSTR(expiry_date,1,2) LIKE "04" AND SUBSTR(expiry_date,7,4) LIKE "2013" AND NOT(expiry_date = "") AND NOT(expiry_date = "n/a")) as total

FROM (SELECT DISTINCT * FROM household_tbl) AS TI GROUP BY b
Kai Qing
  • 18,793
  • 5
  • 39
  • 57
Alyssa Reyes
  • 2,389
  • 6
  • 27
  • 52

1 Answers1

1

You cannot reference an alias that you assigned to another column so you will need to reference the column name:

SELECT household_connector_id as h_id,
  barangay as b,
  municipality as m,
  (SELECT COUNT(*) 
   FROM household_tbl t
   WHERE t.municipality = TI.municipality  -- changed to column name
    AND SUBSTR(t.expiry_date,1,2) LIKE "04" 
     AND SUBSTR(t.expiry_date,7,4) LIKE "2013" 
     AND NOT(t.expiry_date = "") 
     AND NOT(t.expiry_date = "n/a")) +
  (SELECT COUNT(*) 
   FROM tbl_household_members h
   WHERE h.household_connector_id = TI.household_connector_id   -- changed to column name
    AND SUBSTR(h.expiry_date,1,2) LIKE "04" 
     AND SUBSTR(h.expiry_date,7,4) LIKE "2013" 
     AND NOT(h.expiry_date = "") 
     AND NOT(h.expiry_date = "n/a")) as total
FROM 
(
  SELECT DISTINCT * 
  FROM household_tbl
) AS TI 
GROUP BY barangay
Taryn
  • 242,637
  • 56
  • 362
  • 405