[英]SQL find total count of each type in a column
I'm learning SQL and am stumped on what should be a simple query.我正在学习 SQL,对什么应该是简单的查询感到困惑。 I have a table with the following pattern:我有一个具有以下模式的表:
Id | Type
------------
1 | Red
2 | Blue
3 | Blue
4 | Red
..
I would like to write a query to return a table that counts the total number of instances of each type and returns a table with the following pattern, for example, if 'Blue' occurs in 12 rows, and 'Red' occurs in 16 rows in the table above, the result would be:我想编写一个查询来返回一个表,该表计算每种类型的实例总数并返回一个具有以下模式的表,例如,如果“蓝色”出现在 12 行中,“红色”出现在 16 行中在上表中,结果将是:
Blue | Red
-----------
12 | 16
You could do it this way:你可以这样做:
SELECT Type, COUNT(*) FROM TABLE GROUP BY Type
If you'd like to see the Types in separate columns, you could do this:如果您想在单独的列中查看类型,可以这样做:
SELECT SUM(CASE WHEN Type = 'Blue' THEN 1 ELSE 0 END) AS Blue, SUM(CASE WHEN Type = 'Red' THEN 1 ELSE 0 END) AS Red FROM TABLE
I suggest using count over partition by .我建议使用count over partition by 。 Here's a code I wrote to help my company check for duplicate Technician EmployeeID's and Pincodes, including count and YES/NO columns to allow filtering in excel so they can see what corrections need to be made:这是我编写的代码,用于帮助我的公司检查重复的技术人员 EmployeeID 和 Pincode,包括计数和是/否列,以允许在 excel 中进行过滤,以便他们可以看到需要进行哪些更正:
select
t.TechnicianId, t.TechnicianName, t.Pincode, t.EmployeeID
, [Pincode Count] = count(t.Pincode) over (partition by t.Pincode)
, [Duplicate Pincode?] = case count(t.Pincode) over (partition by t.Pincode) when 1 then 'NO' else 'YES' end
, [EmployeeID Count] = count(t.EmployeeID) over (partition by t.EmployeeID)
, [Duplicate EmployeeID?] = case count(t.EmployeeID) over (partition by t.EmployeeID) when 1 then 'NO' else 'YES' end
from Technicians t
group by t.TechnicianId, t.TechnicianName, t.Pincode, t.EmployeeID
order by 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.