부모와 자식 제품이있는 데이터가 있습니다.
각 부모는 자신의 계정에 고유 코드 (P1)와 링크 코드 (L1)가 있고 부모의 각 자식은 별도의 코드 (C12)를 가지지 만 동일한 계정 번호를 공유합니다.
나는 부모와 자녀를 세고 싶다
다음은 샘플 데이터 세트입니다.
create table #Something
(
Line_no int,
code varchar(5),
AccountNo char(5)
)
일부 샘플 데이터
INSERT #Something
select 12311, 'P1c', 'Ac115' union all
select 12311, 'L1', 'Ac115' union all
select 123, 'C1', 'Ac115' union all
select 1222, 'C1', 'Ac115' union all
select 1243, 'C1', 'Ac115' union all
select 433, 'P1a', 'Ac111' union all
select 433, 'L1', 'Ac111' union all
select 4331, 'C1', 'Ac111' union all
select 543, 'C1', 'Ac222' union all
select 544, 'C1', 'Ac222' union all
select 4322, 'P1b', 'Ac222' union all
select 4322, 'L1', 'Ac222' union all
select 8766,'P1d' , 'Ab111' union all
select 8766,'L1' , 'Ab111' union all
select 8767,'C1', 'Ab111' union all
select 8789,'P1d', 'Ab119' union all
select 8766,'L1', 'Ab119' union all
select 876654,'C1', 'Ab119' union all
select 876655,'C1', 'Ab119' union all
select 876698,'P1a', 'Ab117' union all
select 876698,'L1', 'Ab117' union all
select 987,'C1', 'Ab117' union all
select 555444,'P1d','Xcv' union all
select 555444,'L1','Xcv' union all
select 6754,'C1','Xcv'
SELECT * from #Something
drop table #Something
원하는 출력은 다음과 같습니다.
[Parent code] [Parent line Count] [Child line Count]
P1c 1 3
P1a 2 2
P1b 1 2
P1d 3 4
감사
매우 이상한 스키마이지만이 쿼리는 원하는 것을 제공합니다.
with cte as (
select
max(case when code like 'P%' then code end) as [Parent code],
count(case when code like 'P%' then code end) as [Parent line Count],
count(case when code like 'C%' then code end) as [Child line Count]
from Something
group by AccountNo
)
select
[Parent code],
sum([Parent line Count]) as [Parent line Count],
sum([Child line Count]) as [Child line Count]
from cte
group by [Parent code]
공통 테이블 표현식이 마음에 들지 않으면 하위 쿼리를 사용할 수 있습니다.
select
[Parent code],
sum([Parent line Count]) as [Parent line Count],
sum([Child line Count]) as [Child line Count]
from (
select
max(case when code like 'P%' then code end) as [Parent code],
count(case when code like 'P%' then code end) as [Parent line Count],
count(case when code like 'C%' then code end) as [Child line Count]
from Something
group by AccountNo
) as A
group by [Parent code]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다