[英]How to query for rows that have highest column value among rows that have same value for one of the columns v.2
Still a journeyman to SQL here. 仍然是SQL的熟练手。 I have a temp table named #everything which has the following data.
我有一个名为#everything的临时表,该表具有以下数据。 (headers abbreviated).
(标题缩写)。 The temp table has many more columns than this.
临时表中的列比这多得多。
hh_key sub_id tier
1 1234 T1
2 2345 T2
3 4567 T4
3 4568 T3
I want to return the rows with the 'best' tier. 我想返回具有“最佳”层的行。 In my case best has the lowest number after the 'T'.
就我而言,最好的数字在“ T”之后最低。 So here are my desired results:
所以这是我想要的结果:
hh_key sub_id tier
1 1234 T1
2 2345 T2
3 4568 T3
I know that this exact issue was asked and resolved here: previous question but the syntax provided in the answer does not work for me. 我知道这个确切的问题已在此处提出并解决: 上一个问题,但答案中提供的语法对我不起作用。 All records are returned, not just the ones with the desired values.
返回所有记录,而不仅仅是具有所需值的记录。
This would be my version of the previous answer and it does not return a subset of values. 这将是我上一个答案的版本,并且不会返回值的子集。 Everything is returned.
一切都返回了。
Select household_key, sm_subscription_id ,mytier
from #everything
where Mytier is not null
and Mytier IN (select MIN(mytier) from #everything group by household_key)
order by household_key
Could the fact that I have more than those 3 columns requested from the table be a factor? 原因是我表中所请求的列多于那三列吗?
You can use ROW_NUMER()
: 您可以使用
ROW_NUMER()
:
SUBSTRING(tier, 2, LEN(tier) - 1)
will extract the numbers after 'T'
. SUBSTRING(tier, 2, LEN(tier) - 1)
将提取'T'
之后的数字。 You can use the extracted string and CAST
it to INT
and use it in the ORDER BY
clause of your ROW_NUMBER
. 您可以使用提取的字符串并将其
CAST
为INT
,然后在ROW_NUMBER
的ORDER BY
子句中使用它。
WITH Cte AS(
SELECT *,
rn = ROW_NUMBER() OVER(
PARTITION BY hh_key
ORDER BY CAST(SUBSTRING(tier, 2, LEN(tier) - 1) AS INT)
)
FROM #everything
)
SELECT
hh_key, sub_id, tier
FROM Cte
WHERE rn = 1
DROP TABLE #everything
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.