I'm trying to use temp table to simplify my query. At the beginning I used WITH, which was not recognized if I'm not joining each table specifically. What's the best way to approach this query? what's wrong with this syntax?
For the account that purchased the most (in total over their lifetime as a customer) standard_qty paper, how many accounts still had more in total purchases?
create temp table t1 as (
SELECT
a.id as account_id,
SUM(o.standard_qty) as all_std_qty
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
GROUP BY
1
order by
2 desc
limit
1
)
create temp table t2 as (
SELECT
a.id as account_id,
SUM(o.total) as total_purchases
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
GROUP BY
1
)
create temp table t3 as (
SELECT
t1.account_id,
t2.total_purchases as total_pur FROM
t1
JOIN t2
ON (t1.account_id = t2.account_id)
)
SELECT
count(a.id) as count_ids
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
WHERE
o.total > t3.total_pur
I think you missed a join with table t3 and you used it on where clause thats the problem ,can you please try with below query
WITH t1 as (
SELECT
a.id as account_id,
SUM(o.standard_qty) as all_std_qty
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
GROUP BY
1
order by
2 desc
limit
1
), t2 as (
SELECT
a.id as account_id,
SUM(o.total) as total_purchases
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
GROUP BY
1
), t3 as (
SELECT
t1.account_id,
t2.total_purchases as total_pur FROM
t1
JOIN t2
ON (t1.account_id = t2.account_id)
)
SELECT
count(a.id) as count_ids
FROM
accounts a
JOIN orders o ON (a.id = o.account_id)
inner join t3 on a.id=t3.account_id
WHERE
o.total > t3.total_pur
Related
with t1 as (
SELECT *
from claim fc
inner join drug_product d
on d.drug_id = d.drug_id
AND d.id = d.id
inner join pharmacy pha
on fc.pharmacy_id = pha.pharmacy_id
and fcnum = pha.num
),
t2 as (
Select d_memberid,
fill_dt,
num,
d_drug_id,
count(distinct device_type) as device_count,
count(device_type),
count(distinct claim_ID)as claim_count
from t1
group by
d_member_id,
fill_dt,
num
)
Select t1.*,
t2.device_count,
d.*
from t1
inner join t2
on t1.num = t2.num
and t1.fill_dt = t2.fill_dt
and t1.d_member_id = t2.d_member_id
inner join drug_product d
on t1.d_drug_id = d.d_drug_id
order by claim_count desc
column ambiguouly defined. Im trying to find if there dup drug fill on the same day. line 54 column 32
column ambigously defined. I wonder if my joins are incorrect. for t1 i join 3 different table for t2 is from the first table. outcome should be a join of the t1 and t2
d_member_hq_id is not prefixed by a table alias, and could be causing the problem if the column name exists in more than 1 table in the from clause. There are other columns which are also not qualified, it is a good practice to qualify all columns to avoid this error.
I was given sample SQL which does not seem to do what I need.
Big table has 4 million rows and small table has 600 thousand rows.
/* Sample code: (I was given this sample by a senior analyst) */
SELECT SUM(BigTable.VALUE)
FROM BigTable INNER JOIN SmallTable
WHERE BigTable.ID = SmallTable.ID
AND BigTable.VALUATION_DATE IN
(SELECT MAX(VALUATION_DATE)
FROM BigTable)
GROUP BY BigTable.ID
/* My code: (I placed a WHERE in the inner query) */
SELECT BigTable.ID, SUM(BigTable.VALUE)
FROM BigTable INNER JOIN SmallTable
WHERE BigTable.ID = SmallTable.ID
AND BigTable.VALUATION_DATE IN
(SELECT MAX(VALUATION_DATE)
FROM BigTable INNER JOIN SmallTable
WHERE BigTable.ID = SmallTable.ID)
GROUP BY BigTable.ID
If ID xyz has three accounts with values $1, $2, $3 respectively on the most recent date, I want to return the sum of all accounts on that date: xyz, $6
So the INNER JOIN syntax you are using I believe is incorrect. After the INNER JOIN table that will be joined, you need to state ON what columns you wish to join the tables on.
The following query is the correct syntax (although it may not be correct for your implementation).
SELECT BigTable.ID, SUM(BigTable.VALUE)
FROM BigTable INNER JOIN SmallTable
ON BigTable.ID = SmallTable.ID
WHERE BigTable.VALUATION_DATE IN
(SELECT MAX(VALUATION_DATE)
FROM BigTable INNER JOIN SmallTable
ON BigTable.ID = SmallTable.ID)
GROUP BY BigTable.ID
Only when you are doing cross joins, and natural joins do you not use the ON keyword and only use the WHERE command.
You should avoid the where clause and use the ON Clause
SELECT SUM(BigTable.VALUE)
FROM BigTable
INNER JOIN SmallTable ON BigTable.ID = SmallTable.ID
AND BigTable.VALUATION_DATE = (
SELECT MAX(VALUATION_DATE)
FROM BigTable)
and youn should not use a group by id ..
Use window functions:
SELECT b.ID, b.VALUE
FROM (SELECT b.*,
ROW_NUMBER() OVER (PARTITION BY b.id ORDER BY b.VALUATION_DATE DESC) as seqnum
FROM BigTable b
) b JOIN
SmallTable s
ON b.ID = s.ID
WHERE b.seqnum = 1;
I don't think aggregation is necessary. But, if you have multiple values on the same date for the same id, then:
SELECT b.ID, SUM(b.VALUE)
FROM (SELECT b.*,
RANK() OVER (PARTITION BY b.id ORDER BY b.VALUATION_DATE DESC) as seqnum
FROM BigTable b
) b JOIN
SmallTable s
ON b.ID = s.ID
WHERE b.seqnum = 1
GROUP BY b.id;
I'm coding a query to retrieve sum of all components price used to make a product, but I have a problem with this query. WHen I code a query to retrieve the price of each component (quantity used * unit price) I retrieve the correct result:
SELECT t1.coc_codigo, SUM(t1.pmc_precio) * SUM(t2.ccm_cantidad)
FROM precios_componentes_costos t1
JOIN composicion_tipos_masa t2
ON (t1.coc_codigo = t2.coc_codigo)
WHERE t1.coc_codigo IN (SELECT coc_codigo
FROM composicion_tipos_masa t3
JOIN tipos_masas t4
ON (t3.tms_codigo =t4.tms_codigo)
WHERE t3.tms_codigo = 'MMS')
GROUP BY t1.coc_codigo
ORDER BY 1 ASC;
But when I try to summarized all records I retrieve a wrong result:
SELECT SUM(t1.pmc_precio) * SUM(t2.ccm_cantidad) AS TOTAL
FROM precios_componentes_costos t1
JOIN composicion_tipos_masa t2
ON (t1.coc_codigo = t2.coc_codigo)
WHERE t1.coc_codigo IN (SELECT coc_codigo
FROM composicion_tipos_masa t3
JOIN tipos_masas t4
ON (t3.tms_codigo =t4.tms_codigo)
WHERE t3.tms_codigo = 'MMS')
ORDER BY 1 ASC;
I would like to retrieve the final result with a query (195.591132). Do you have any idea? Thanks!.
In agreement with the observation from #PM77-1, you need to perform the calculation for each record before you get the sum. Something like this:
SELECT
coc_codigo
, SUM(TOTAL_SUB) AS TOTAL
FROM (
SELECT
t1.coc_codigo
, (t1.pmc_precio * t2.ccm_cantidad) AS TOTAL_SUB
FROM precios_componentes_costos t1
INNER JOIN composicion_tipos_masa t2
ON ( t1.coc_codigo = t2.coc_codigo )
INNER JOIN composicion_tipos_masa t3
ON ( t3.tms_codigo = t1.coc_codigo )
INNER JOIN tipos_masas t4
ON ( t3.tms_codigo = t4.tms_codigo )
WHERE t3.tms_codigo = 'MMS'
GROUP BY t1.coc_codigo
) AS multiplied
Finally the comment from #PM77-1 made I remake my query and the new query is:
SELECT /*t1.coc_codigo,*/ SUM(t1.pmc_precio * t2.ccm_cantidad)
FROM precios_componentes_costos t1
JOIN composicion_tipos_masa t2
ON (t1.coc_codigo = t2.coc_codigo)
WHERE t1.coc_codigo IN (SELECT coc_codigo
FROM composicion_tipos_masa t3
JOIN tipos_masas t4
ON (t3.tms_codigo =t4.tms_codigo)
WHERE t3.tms_codigo = 'MMS')
--GROUP BY t1.coc_codigo
ORDER BY 1 ASC;
This query is correct!!! Thanks everyone for your help.
I want to do an inner join but I do not have any result:
select
t5.tcdv_id, t5.gps_coordx, t5.gps_coordy,
t6.status
from
(
select
t3.tcdv_id tcdv_id, t3.reg_date reg_date,
t4.CONTROLLERCOMM_STATUS status
from
SCS_L_SCSCONTROLLERSTATUS t4
inner join
(
select
t1.tcdv_id tcdv_id,
max(reg_date) reg_date
from
SCS_L_SCSCONTROLLERSTATUS t2
inner join
(
select distinct
tcdv_id
from
SCS_L_SCSCONTROLLERSTATUS
where
tcdv_id not in('C1010000','C10100000')
) t1
on
t1.tcdv_id=t2.tcdv_id
group by
t1.tcdv_id
) t3
on
t3.tcdv_id=t4.tcdv_id and
t3.reg_date=t4.reg_date
) t6
inner join
(
select
t.tcdv_id tcdv_id, t.int_ip int_ip,
b.gps_coordx gps_coordx, b.gps_coordy gps_coordy
from
bits.tms_m_node b
inner join
tscs.scs_m_intlc#"BITS_TSCS.CORE.TMC.LOCAL" t
on
t.node_id=b.node_id
) t5
on
t5.tcdv_id=t6.tcdv_id;
I'm trying to join these two SQL queries together. My data is at https://policevideorequests.cartodb.com/tables/seattle_police_govqa_audit_trails which has a Postgresql SQL API.
SELECT
t1.customer_id, t1.c,
t2.customer_name, t2.customer_email, t2.customer_email_domain
FROM
(SELECT
a.customer_id, count(a.customer_id) as c
FROM
(SELECT customer_id, reference_no
FROM seattle_police_govqa_audit_trails
WHERE customer_id NOT IN (5, 0, -1)
GROUP BY customer_id, reference_no) a
GROUP BY
a.customer_id
ORDER BY
count(a.customer_id) DESC) t1
INNER JOIN
(SELECT DISTINCT
customer_id,
INITCAP(LOWER(SUBSTRING(new_value FROM 'Dear (.*?):</div>'))) as customer_name,
LOWER(SUBSTRING(new_value FROM 'login:<b>(.*?)</b>')) as customer_email,
LOWER(SUBSTRING(new_value FROM 'login:<b>.*?#(.*?)</b>')) as customer_email_domain
FROM
seattle_police_govqa_audit_trails
WHERE
SUBSTRING(new_value FROM 'Dear (.*?):</div>') IS NOT NULL) t2 ON t1.customer_id = t2.customer_id
ORDER BY
t1.c DESC
SELECT DISTINCT
t1.new_value as requester_type, t2.customer_id
FROM
(SELECT
reference_no, new_value
FROM
seattle_police_govqa_audit_trails
WHERE
action_desc = 154) t1
INNER JOIN
(SELECT
reference_no, customer_id
FROM
seattle_police_govqa_audit_trails
WHERE
customer_id NOT IN (0, -1, 5)) t2 ON t1.reference_no = t2.reference_no
My attempt at joining the two:
SELECT t1.customer_id,t3.requester_typer,t1.c,t2.customer_name,t2.customer_email,t2.customer_email_domain,t2.customer_email_domain_tld FROM (SELECT a.customer_id,count(a.customer_id) as c FROM (SELECT customer_id, reference_no FROM seattle_police_govqa_audit_trails WHERE customer_id NOT IN (5,0,-1) GROUP BY customer_id,reference_no) a GROUP BY a.customer_id ORDER BY count(a.customer_id) DESC) t1
INNER JOIN (SELECT DISTINCT customer_id,INITCAP(LOWER(SUBSTRING(new_value FROM 'Dear (.*?):</div>'))) as customer_name,LOWER(SUBSTRING(new_value FROM 'login:<b>(.*?)</b>')) as customer_email, LOWER(SUBSTRING(new_value FROM 'login:<b>.*?#(.*?)</b>')) as customer_email_domain, LOWER(SUBSTRING(new_value FROM 'login:<b>.*?#.*?\.(.*?)</b>')) as customer_email_domain_tld FROM seattle_police_govqa_audit_trails WHERE SUBSTRING(new_value FROM 'Dear (.*?):</div>') IS NOT NULL) t2
ON t1.customer_id = t2.customer_id ORDER BY t1.c DESC
INNER JOIN (SELECT DISTINCT t1.new_value as requester_type,t2.customer_id FROM (SELECT reference_no,new_value FROM seattle_police_govqa_audit_trails WHERE action_desc = 154) t1
INNER JOIN (SELECT reference_no,customer_id FROM seattle_police_govqa_audit_trails WHERE customer_id NOT IN (0,-1,5)) t2
ON t1.reference_no = t2.reference_no) as t3
ON t2.customer_id = t3.customer_id
I get the error "syntax error near INNER"
The problem in your SQL query is that you tried to keep ORDER BY in the middle. The ORDER BY clause must be moved all the way to the back of the query, because ordering is applied to the entire query, not to its parts.
Try this:
SELECT t1.customer_id,t3.requester_typer,t1.c,t2.customer_name,t2.customer_email,t2.customer_email_domain,t2.customer_email_domain_tld FROM (SELECT a.customer_id,count(a.customer_id) as c FROM (SELECT customer_id, reference_no FROM seattle_police_govqa_audit_trails WHERE customer_id NOT IN (5,0,-1) GROUP BY customer_id,reference_no) a GROUP BY a.customer_id ORDER BY count(a.customer_id) DESC) t1
INNER JOIN (SELECT DISTINCT customer_id,INITCAP(LOWER(SUBSTRING(new_value FROM 'Dear (.*?):</div>'))) as customer_name,LOWER(SUBSTRING(new_value FROM 'login:<b>(.*?)</b>')) as customer_email, LOWER(SUBSTRING(new_value FROM 'login:<b>.*?#(.*?)</b>')) as customer_email_domain, LOWER(SUBSTRING(new_value FROM 'login:<b>.*?#.*?\.(.*?)</b>')) as customer_email_domain_tld FROM seattle_police_govqa_audit_trails WHERE SUBSTRING(new_value FROM 'Dear (.*?):</div>') IS NOT NULL) t2
ON t1.customer_id = t2.customer_id
INNER JOIN (SELECT DISTINCT t1.new_value as requester_type,t2.customer_id FROM (SELECT reference_no,new_value FROM seattle_police_govqa_audit_trails WHERE action_desc = 154) t1
INNER JOIN (SELECT reference_no,customer_id FROM seattle_police_govqa_audit_trails WHERE customer_id NOT IN (0,-1,5)) t2
ON t1.reference_no = t2.reference_no) as t3
ON t2.customer_id = t3.customer_id
ORDER BY t1.c DESC