My sub-query gets me the brand name and sum of the of the sales amount from 2013. My main query is trying to get the brand name and the highest sales amount from that year but this will return duplicate because the query will try to get the max(amount) for each brand name. How do I filter it so it will just return the highest amount with only one brand name? This is my query so far, any pointers would be helpful. Thanks!
SELECT
maxamt.brnd_nm,
MAX(maxamt.amt) AS amt
FROM
(
SELECT
c.brnd_nm AS BRND_NM,
SUM(b.sales_amt) AS AMT
FROM prd.client A
INNER JOIN db1.table1 B
ON b.pty_key = a.pty_key
INNER JOIN db1.table2 c
ON b.d_key = c.d_key
INNER JOIN db1.table3 d
ON b.posat_key = d.posat_key
INNER JOIN db1.table4 e
ON b.frmly_key = e.frmly_key
WHERE B.date BETWEEN '2013-01-01'
AND '2013-12-31'
AND b.C_ID IN ( 'abc', 'def', 'wqs')
GROUP BY 1
) MaxAmt
GROUP BY 1
You don't need a subquery, just use ORDER BY
and LIMIT
:
SELECT
c.brnd_nm AS BRND_NM,
SUM(b.sales_amt) AS AMT
FROM prd.client A
INNER JOIN db1.table1 B
ON b.pty_key = a.pty_key
INNER JOIN db1.table2 c
ON b.d_key = c.d_key
INNER JOIN db1.table3 d
ON b.posat_key = d.posat_key
INNER JOIN db1.table4 e
ON b.frmly_key = e.frmly_key
WHERE B.date BETWEEN '2013-01-01'
AND '2013-12-31'
AND b.C_ID IN ( 'abc', 'def', 'wqs')
GROUP BY BRND_NM
ORDER BY AMT DESC
LIMIT 1
Can't you use the TOP
operator?:
SELECT TOP 1 *
FROM ( SELECT c.brnd_nm AS BRND_NM,
SUM(b.sales_amt) AS AMT
FROM prd.client A
INNER JOIN db1.table1 B
ON b.pty_key = a.pty_key
INNER JOIN db1.table2 c
ON b.d_key = c.d_key
INNER JOIN db1.table3 d
ON b.posat_key = d.posat_key
INNER JOIN db1.table4 e
ON b.frmly_key = e.frmly_key
WHERE B.date BETWEEN '2013-01-01'
AND '2013-12-31'
AND b.C_ID IN ( 'abc', 'def', 'wqs')
GROUP BY c.brnd_nm) MaxAmt
ORDER BY AMT DESC
You can use QUALIFY plus ROW_NUMBER:
SELECT
c.brnd_nm AS BRND_NM,
SUM(b.sales_amt) AS AMT
FROM prd.client A
INNER JOIN db1.table1 B
ON b.pty_key = a.pty_key
INNER JOIN db1.table2 c
ON b.d_key = c.d_key
INNER JOIN db1.table3 d
ON b.posat_key = d.posat_key
INNER JOIN db1.table4 e
ON b.frmly_key = e.frmly_key
WHERE B.date BETWEEN '2013-01-01'
AND '2013-12-31'
AND b.C_ID IN ( 'abc', 'def', 'wqs')
GROUP BY 1
QUALIFY
ROW_NUMBER()
OVER (ORDER BY AMT DESC) = 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.