如何获得结果第一行中不同值的计数

问题描述

我想检查文档的颜色和城市是否为最大数量的倍数。如果是,我想设置一个位为 1,如果不是,它应该是 0

示例数据:

Code doc year amount colour city
AB   123 2021 485    Red    Paris
AB   123 2021 416    Red    Paris
AB   123 2021 729    Red    London
AB   123 2021 645    Red    Bengaluru

预期输出: 我想要一行输出

Code Doc Year Amount Colour City  Col_Mul City_Mul 
AB   123 2021 729    Red    London 0       1

数量、颜色和城市应为最大值。

我尝试过的: 为了获取一行中的数据,我使用了行号并按最大数量排序并选择了行号为一的数据。但在那之后,我对颜色和城市列使用了密集排名。但我没有得到预期的输出

解决方法

您可以使用 CROSS APPLY 并获取如下数据:

感谢@Gayani 提供测试数据。

select TOPROW.*,case when T1.colorcount > 1 THEN 1 else 0 end as Multi_color,case when T2.citycount > 1 THEN 1 else 0 end as Multi_city
 from
 (SELECT TOP 1 * FROM tes_firstRow
 order by amount desc) as toprow
cross apply
(
SELECT count(distinct color) from tes_firstrow WHERE doc = toprow.doc
) as t1(colorcount)
cross apply
(
SELECT count(distinct city) from tes_firstrow WHERE doc = toprow.doc
) as t2(citycount)
代码 文档 金额 颜色 城市 多色 多城市
AB 123 2021 729 红色 伦敦 0 1
,

我希望这个代码示例能帮助你解决这个问题。 请尝试下面的代码,让我知道它是否对您的需要有帮助。我在这里使用了临时表。您可以使用任何技术来构建逻辑。 CTE(通用表表达式)或派生表。

CREATE TABLE tes_firstRow
(
    Code varchar(100),doc int,[year] int,amount int,color varchar(100),City varchar(100)
)

insert into  tes_firstRow values  ('AB',123,2021,485,'RED','PARIS')
insert into  tes_firstRow values  ('AB',416,729,'LONDON')
insert into  tes_firstRow values  ('AB',645,'BENGALURU')

SELECT 
    RANK() OVER (PARTITION BY  Code,doc,[year] ORDER BY amount DESC) AS [rank],Code,[year],amount,color,City 
INTO #temp_1
FROM tes_firstRow


 SELECT 
 [#temp_1].[Code],[#temp_1].[doc],[#temp_1].[year],[#temp_1].[amount],[#temp_1].[color],[#temp_1].[City],(Select COUNT(Distinct [#temp_1].[color] ) where  [#temp_1].[rank] = 1 ) as Col_Mul,(Select COUNT(Distinct [#temp_1].[City]) where  [#temp_1].[rank] = 1)  as City_Mul,1 as City_Mul
 FROM  #temp_1 
 WHERE #temp_1.[rank] = 1
  group by   [#temp_1].[Code],[#temp_1].[rank] 

     DROP TABLE #temp_1

 Result:

Result:

,

你去吧。奇怪的要求...

SELECT T.Code,Doc,Year,MAX(T.Amount) Amount,(SELECT TOP 1 Colour FROM T as X WHERE Amount = MAX(T.Amount)) Colour,(SELECT TOP 1 City FROM T as X WHERE Amount = MAX(T.Amount)) City,CASE WHEN COUNT(DISTINCT T.Colour) > 1 THEN 1 ELSE 0 END as Col_Mul,CASE WHEN COUNT(DISTINCT T.City) > 1 THEN 1 ELSE 0 END as City_Mul
FROM T
GROUP BY T.Code,Year
,

我认为您只想要窗口函数与条件聚合相结合:

select code,year,max(amount),max(case when seqnum = 1 then color end) as color,max(case when seqnum = 1 then city end) as city,(case when seqnum = 1 and color_count > 1 then 1 else 0 end) as color_dup,(case when seqnum = 1 and city_count > 1 then 1 else 0 end) as city_dup,from (select t.*,row_number() over (partition by code,year order by amount desc) as seqnum,count(*) over (partition by code,color) as color_count,city) as city_count
      from t
     ) t
group by code,year;

我实际上不确定在值是否重复时是否需要 1,因此这些值可能会倒退。