Count Distinct Over partition

时间:2018-01-06 01:57:33

标签: sql-server windows function

我用windows函数尝试这个代码,但是我收到了一个错误 我想要的是根据分区摘要和详细信息计算不同的customerID - 它看起来我在过分区中遗漏了一些东西 (SQL Server 2016)

谢谢, Oded Dror

代码在这里:

Drop table if exists #T_Test
Create table #T_Test(
     [Type] varchar(50) null,
     SubType varchar(50) null,
     CustomerID int null
)
Insert into #T_Test ([Type],[SubType],[CustomerID]) values
('TypeA','SubTypeA',390),
('TypeA','SubTypeA',107),
('TypeB','SubTypeB',3),
('TypeB','SubTypeC',3),
('TypeB','SubTypeB',107),
('TypeB','SubTypeC',107),
('TypeB','SubTypeB',390),
('TypeB','SubTypeC',390),
('TypeB','SubTypeC',718),
('TypeB','SubTypeB',100120),
('TypeB','SubTypeC',100120),
('TypeB','SubTypeC',100120),
('TypeC','SubTypeD',107),
('TypeC','SubTypeE',100120),
('TypeC','SubTypeE',718)

--Total goes here - If CustomerID appears in multiple partition it will count once
Select ' Grand Total' as [Type],
              '' as SubType,
              Count(Distinct CustomerID ) as TotalCustomers,
              Count(CustomerID) over (partition by CustomerID,Type Order by CustomerID) as TotalType,
              Count(CustomerID) over (partition by CustomerID,Type,SubType Order by CustomerID) as TotalSubType
From #T_Test

Union All
-- Details goes here - same as Total if customer appers in multiple partiotion it will count once
Select  [Type],
        SubType,
        Count(Distinct CustomerID) as TotalCustomers,
        Count(CustomerID) over (partition by CustomerID,Type Order by CustomerID) as TotalType,
        Count(CustomerID) over (partition by CustomerID,Type,SubType Order by CustomerID) as TotalSubType
From     #T_Test
Group by Type,
         SubType

2 个答案:

答案 0 :(得分:0)

试试这个

;WITH CTE
AS
(
    SELECT
        [Type],
        SubType,
        TotCnt= COUNT(1) OVER(PARTITION BY [Type]),
        TotSubCnt= COUNT(1) OVER(PARTITION BY [Type],SubType),
        RN = ROW_NUMBER() OVER(PARTITION BY [Type],SubType,[CustomerID] ORDER BY [Type],SubType)
        FROM #T_Test
)
SELECT
    [Type],
    SubType,
    TotCnt,
    TotSubCnt,
    DistCustomer = SUM(CASE WHEN RN =1 THEN 1 ELSE 0 END) OVER(PARTITION BY [Type])
    FROM CTE

答案 1 :(得分:0)

--I hope Customerid is no need to group by

Select ISNULl([Type],'GRAND TOTAL')[Type],
       ISNULL([SubType],'=') as [SubType],
       COUNT(CustomerID) as SubTotal,
       COUNT(distinct CustomerID) AS TotalCustomers 
  FROM #T_test GROUP BY ROLLUP([Type],[SubType]) ORDER BY [Type],[SubType] DESC