我的子查询获取了2013年的品牌名称和销售额总和。我的主要查询是尝试获取该年度的品牌名称和最高销售额,但这将返回重复,因为查询将尝试获取每个品牌名称的最大值(金额)。如何过滤它以便只返回一个品牌名称的最高金额?到目前为止,这是我的查询,任何指针都会有所帮助。谢谢!
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
答案 0 :(得分:2)
您不需要子查询,只需使用ORDER BY
和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
答案 1 :(得分:2)
您不能使用TOP
运算符吗?:
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
答案 2 :(得分:1)
您可以使用QUALIFY加上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