简体   繁体   English

有没有办法计算唯一对并按其他列分组

[英]Is there a way to count unique pairs and group by other columns

I am trying to find the number of unique combinations in each Station by year.我试图按年查找每个站中唯一组合的数量。 My data looks like this:我的数据如下所示:

Track Title曲目名称 Main Artist主要艺术家 Station车站 Year
Track A轨道A Artist A艺术家A A A 2020 2020
Track A轨道A Artist A艺术家A A A 2020 2020
Track B B轨 Artist A艺术家A A A 2020 2020
Track B B轨 Artist A艺术家A A A 2020 2020
Track A轨道A Artist B艺术家乙 A A 2020 2020
Track A轨道A Artist B艺术家乙 A A 2020 2020
Track B B轨 Artist B艺术家乙 A A 2020 2020
Track B B轨 Artist B艺术家乙 A A 2020 2020
Track A轨道A Artist A艺术家A A A 2019 2019
Track A轨道A Artist A艺术家A A A 2019 2019
Track A轨道A Artist A艺术家A A A 2019 2019

I need just a count of each unique combination of Track Title and Main Artist per station per year:我只需要计算每年每个电台的曲目标题和主要艺术家的每个独特组合:

Count数数 Station车站 Year
4 4个 A A 2020 2020
1 1个 A A 2019 2019

I am on a SQL Server using SSMS.我在使用 SSMS 的 SQL 服务器上。

The closest I had gotten to the result before was我之前最接近结果的是

SELECT 
    Count(distinct [Track Title]) as Count,
        [Main Artist],
        [Station Code]
        [YEAR]

FROM table

GROUP BY [Main Artist], [Station Code], [Year]

And then pivoting this result in Excel to do the sums, but I was unsure of how to incorporate it into a single query.然后在 Excel 中旋转这个结果来做总和,但我不确定如何将它合并到一个查询中。

Remove duplicate rows in a derived table (ie the subquery).删除派生表(即子查询)中的重复行。 GROUP BY its result: GROUP BY其结果:

select count(*) cnt, station, year
from
(
    select distinct * from table
) dt
group by station, year

Concatenate the 2 values and then COUNT the DISTINCT values:连接 2 个值,然后DISTINCT COUNT

SELECT COUNT(DISTINCT CONCAT(TrackTitle,'|',MainArtist)) AS [Count],
       Station,
       [Year]
FROM dbo.YourTable
GROUP BY Station,
         [Year];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM