我总共有10个小组。分组编号(列A
)在列Type
中的每个不同值处重新开始。我希望将所有类型的10个组除以100,然后按每个组中的条目数(行数)得到每组的结果数。
列A + Type
是我的组标识符,列B
是我想要的最终结果。
我尝试了一些基于嵌套查询的变体方程式,其中的计数按A
和type
分组,但我并没有理解如何将它们整合在一起。
ID A B TYPE
01 1 10 APPLE
02 2 5 APPLE
03 2 5 APPLE
04 3 2.5 APPLE
05 3 2.5 APPLE
06 3 2.5 APPLE
07 3 2.5 APPLE
08 4 5 APPLE
09 4 5 APPLE
10 5 10 APPLE
11 1 5 ORANGE
12 1 5 ORANGE
13 2 10 ORANGE
14 3 5 ORANGE
15 3 5 ORANGE
16 4 2.5 ORANGE
17 4 2.5 ORANGE
18 4 2.5 ORANGE
19 4 2.5 ORANGE
20 5 10 ORANGE
答案 0 :(得分:2)
<强> EDITED 强>
修复附加行
21 5 ** ORANGE
WITH subGroup as (
SELECT [TYPE], [A], count([TYPE]) as total
FROM Table1
GROUP BY [TYPE], [A]
),
totalGroup as (
SELECT count(DISTINCT [TYPE] + CAST([A] as varchar(10))) as total
FROM Table1
)
SELECT t.ID, t.[A], (100.0 / tg.total / s.total) as [B], t.[TYPE]
FROM Table1 t
inner join subGroup s
on t.[Type] = s.[Type]
and t.[A] = s.[A]
, totalGroup tg
<强>输出强>
| ID | A | B | TYPE |
|----|---|-----|--------|
| 1 | 1 | 10 | APPLE |
| 2 | 2 | 5 | APPLE |
| 3 | 2 | 5 | APPLE |
| 4 | 3 | 2.5 | APPLE |
| 5 | 3 | 2.5 | APPLE |
| 6 | 3 | 2.5 | APPLE |
| 7 | 3 | 2.5 | APPLE |
| 8 | 4 | 5 | APPLE |
| 9 | 4 | 5 | APPLE |
| 10 | 5 | 10 | APPLE |
| 11 | 1 | 5 | ORANGE |
| 12 | 1 | 5 | ORANGE |
| 13 | 2 | 10 | ORANGE |
| 14 | 3 | 5 | ORANGE |
| 15 | 3 | 5 | ORANGE |
| 16 | 4 | 2.5 | ORANGE |
| 17 | 4 | 2.5 | ORANGE |
| 18 | 4 | 2.5 | ORANGE |
| 19 | 4 | 2.5 | ORANGE |
| 20 | 5 | 5 | ORANGE |
| 21 | 5 | 5 | ORANGE |
答案 1 :(得分:1)
希望此查询有帮助
Select At.A, B = CAST(tot as float) / Cnt, At.Type
From Test AT
Inner Join
(Select A, Type, Cnt = Count(*) From Test
Group By A, Type) BT On AT.A = BT.A and AT.Type = BT.Type
Inner Join
(Select Type, Tot = Count(A) From Test
Group By Type) CT On CT.Type = AT.Type`
答案 2 :(得分:1)
如果您的SQL Server是2008 +:
,您可以使用窗口函数来执行此操作SELECT
ID,
A,
(COUNT(*) OVER (PARTITION BY TYPE))/(COUNT(*) OVER (PARTITION BY A,TYPE)) as B,
TYPE
FROM <table>
order by TYPE, A asc
要添加的编辑:我真的不明白“除以100 ......”部分,但这里的数学符合您想要的结果...所以我认为它的效果相同,对吗?