How to select count of Label where Part is the same?
Part | Label
------+-------
a | L1
a | L2
a | L3
b | L1
b | L2
Expected results:
Part | LabelCount
------+------------
a | 3
b | 2
Notes: All data types are strings. I've tried partitioning to get the max row number, but the MAX function on ROW_NUMBER() is unresponsive the way I've been doing it, and it's just been returning all rows whether I use MAX or not.
;WITH RowNumCTE AS
(
SELECT
[PartName],
ROW_NUMBER() OVER (PARTITION BY [Part] ORDER BY [Label] ASC) AS rn
FROM
[PartTable]
)
SELECT DISTINCT
[Part],
MAX([rn]) AS [LabelCount]
FROM
RowNumCTE
GROUP BY
[Part], [rn]
Actual results:
Part | LabelCount
------+------------
a | 1
a | 2
a | 3
b | 1
b | 2
I've run down the list of similar questions in StackOverflow, like this one , but don't see how to apply the answers to this situation.
You seem to just want group by
:
select part, count(*) as labelcount
from t
group by part;
If you have duplicate labels on a part, then:
select part, count(distinct label)
. . .
simple group by
select part,count(*) from t
group by part
Your approach to the expected o/p is wrong and very complex.
Your desired o/p is no where related to sub partitioning of groups as you have done via partition by etc but was rather a simple group by
as already by the above answers.
select part,count(*) from t
group by part -- as only partwise
count is required
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.