我会切入正确的追逐:我有一个选择我正在写一个相当冗长的where子句,我想要做的是计算百分比。
所以我需要的是所有结果的计数,然后是我的每个不同的计数。
SELECT distinct count(*)
FROM mytable
WHERE mywhereclause
ORDER BY columnIuseInWhereClause
可以很好地获取每个单独的值,但我想避免做像
这样的事情Select (Select count(*) from mytable WHERE mywhereclause),
distinct count(*)
FROM mytable
WHERE mywhereclause
因为我两次使用相同的where子句,这似乎是不必要的。
这是针对OracleDB的,但我只使用标准的SQL语法,如果我可以提供帮助,我没有特定的数据库。
感谢任何想法。
编辑: 样本数据
__ID__,__someValue__
1 | A
2 | A
3 | B
4 | C
我希望A,B,C的出现是数字以及总数。
__CountAll__,__ACounts__,__BCounts__,__CCounts__
4 | 2 | 1 | 1
所以我可以去
100% | 50% | 25% | 25%
最后一部分我可以自己解决。请原谅我缺乏经验甚至是逻辑思维,这是一大早。 ;)
EDIT2: 我确实已经写了一个有效的查询,但是很笨拙,只要是所有神圣的哎呀,这个是用于尝试分组的。
答案 0 :(得分:1)
尝试:
select count(*) as CountAll,
count(distinct SomeColumn) as CoundDistinct -- The DISTINCT goes inside the brackets
from myTable
where SomeOtherColumn = 'Something'
答案 1 :(得分:0)
使用case
表达式进行条件计数:
select count(*) as CountAll,
count(case when someValue = 'A' then 1 end) as ACounts,
count(case when someValue = 'B' then 1 end) as BCounts,
count(case when someValue = 'C' then 1 end) as CCounts
FROM mytable
WHERE mywhereclause
将其包装在派生表中以轻松完成%部分:
select 100,
ACounts * 100 / CountAll,
BCounts * 100 / CountAll,
CCounts * 100 / CountAll
from
(
select count(*) as CountAll,
count(case when someValue = 'A' then 1 end) as ACounts,
count(case when someValue = 'B' then 1 end) as BCounts,
count(case when someValue = 'C' then 1 end) as CCounts
FROM mytable
WHERE mywhereclause
) dt
答案 2 :(得分:0)
这是使用窗口功能的另一种选择:
with data_table(ID, some_value)
AS
(SELECT 1,'A' UNION ALL
SELECT 2,'A' UNION ALL
SELECT 3,'B' UNION ALL
SELECT 4,'C'
)
SELECT DISTINCT [some_value],
COUNT([some_value]) OVER () AS Count_All,
COUNT([some_value]) OVER (PARTITION BY [some_value]) AS 'Counts' FROM [data_table]
ORDER BY [some_value]
优点是您不必硬编码[some_value]