简体   繁体   English

SQL:为另一列选择不同的值

[英]SQL: Selecting distinct values for another column

I'm trying to determine how many unique values from one column can be grouped by values in another column. 我正在尝试确定可以将一列中的多少个唯一值按另一列中的值进行分组。

There are many columns in my sheet, but the ones I'm interested in are: 'department' and 'user' 我的工作表中有很多列,但我感兴趣的列是:“部门”和“用户”

How the data is that for these two columns, there are repeat users with the same department. 对于这两列的数据如何,有相同部门的重复用户。

Eg. 例如。

Department    User

Insights      Mike

Insights      Mike

Insights      Chris

Market        Julie

Research      Will

Research      Sabrina

Research      Bryan

What I would want is the following: 我想要的是以下内容:

Department    DistinctUsers

Insights       2

Market         1

Research       3

My basic SQL knowledge tells me this is the structure of the code: 我的基本SQL知识告诉我这是代码的结构:

SELECT department, COUNT(DISTINCT user) 
FROM Sheet1
GROUP BY department, user

I have seen that people would implement (SELECT DISTINCT User from Sheet1) in the FROM clause, but I have failed to integrate that into the code. 我已经看到人们会在FROM子句中实现(SELECT DISTINCT User from Sheet1)中的(SELECT DISTINCT User from Sheet1) ,但是我未能将其集成到代码中。

Any suggestions or tips is much appreciated! 任何建议或提示,不胜感激!

Thanks! 谢谢!

As mentioned in the comments, you just need to remove users from the group by. 如评论中所述,您只需要将用户从组中删除。

SELECT 
   department, 
   COUNT(DISTINCT [user]) as CT
FROM Sheet1
GROUP BY department

ACCESS 访问

SELECT
   department,
   count([user])
FROM
   (SELECT DISTINCT department, [user] from Sheet1) as x
GROUP BY
   department

您的代码即可完成工作,但无需按用户分组

BEGIN TRAN

CREATE TABLE #TMP (Department  NVARCHAR(50),Name NVARCHAR(50))

INSERT INTO #TMP
SELECT 'Insights', 'Mike' UNION ALL

SELECT 'Insights','Mike' UNION ALL

SELECT 'Insights','Chris'UNION ALL

SELECT 'Market'   ,'Julie' UNION ALL

SELECT 'Research',  'Will'UNION ALL

SELECT  'Research', 'Sabrina'UNION ALL

SELECT  'Research','Bryan'

SELECT * FROM #TMP

SELECT department, COUNT(DISTINCT NAME) 
FROM #TMP
GROUP BY department

ROLLBACK TRAN

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

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