[英]How to aggregate by certain columns and not others in SQL
|other|last|first|program| |其他|最后|第一个|程序|
|cat|Acker|Bob A| |猫|阿克|鲍勃A|
|dog|Acker|Bob|B| |狗|阿克|鲍勃|B|
|reptile|Acker|Bob|A| |爬行动物|阿克|鲍勃|A|
|cat|Birch|Patty|B| |猫|桦木|肉饼|B|
|bunny|Calhoun|Peter|C| |兔子|卡尔霍恩|彼得|C|
BECOMES成为
|other|last|first|program| |其他|最后|第一个|程序|
|cat|Acker|Bob A| |猫|阿克|鲍勃A|
|dog|Acker|Bob|B| |狗|阿克|鲍勃|B|
|cat|Birch|Patty|B| |猫|桦木|肉饼|B|
|bunny|Calhoun|Peter|C| |兔子|卡尔霍恩|彼得|C|
How do you get the above to work?你如何让上述工作? I'm a sql novice.
我是一个sql新手。 I'm trying to get a total count of records by one field based on certain values in other fields but not others.
我试图根据其他字段中的某些值而不是其他字段中的某个字段来获取记录总数。 In the above Tables, I basically want sql to pull out reptile Acker Bob A, because A is already represented as a program by Bob.
在上表中,我基本上是想让sql拉出爬虫Acker Bob A,因为A已经被Bob表示为程序了。 But I don't want the following removed for Bob because these programs are represented exactly once:
但我不希望 Bob 删除以下内容,因为这些程序只表示一次:
cat Acker Bob A
dog Acker Bob B
I've tried this but I can't get it to work:我试过这个,但我无法让它工作:
SELECT program, total, sum(program) as allTotal
FROM mytable
GROUP BY program
HAVING count(program) <= 1
I want my end result to look like this:我希望我的最终结果是这样的:
program total allTotal程序总计 allTotal
A 2 5一个 2 5
B 1 5乙 1 5
C 1 5 1 5
Is this what you want?这是你想要的吗?
select
program,
count(*) total,
(select count(*) from mytable) all_total
from mytable
group by program
It sounds like you want听起来你想要
SELECT program, COUNT(distinct CONCAT(first, last)) AS total, (SELECT COUNT(*) FROM mytable) AS allTotal
FROM mytable
GROUP BY program
By only counting the distinct CONCAT(first, last) it will not count Bob twice in Program A.通过只计算不同的 CONCAT(first, last),它不会在程序 A 中计算 Bob 两次。
The equivalent for some DBs without CONCAT
:一些没有
CONCAT
的等价物:
SELECT program, COUNT(distinct first||last) AS total, (SELECT COUNT(*) FROM mytable) AS allTotal
FROM mytable
GROUP BY program
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.