[英]SQL grouping
I have a table with the following columns: 我有一个包含以下列的表格:
A B C --------- 1 10 X 1 11 X 2 15 X 3 20 Y 4 15 Y 4 20 Y
I want to group the data based on the B and C columns and count the distinct values of the A column. 我想基于B和C列对数据进行分组,并计算A列的不同值。 But if there are two ore more rows where the value on the A column is the same I want to get the maximum value from the B column. 但是,如果有两个或两个以上的行,其中A列的值相同,我想从B列获取最大值。
If I do a simple group by the result would be: 如果按结果进行简单分组,结果将是:
B C Count -------------- 10 X 1 11 X 1 15 X 1 20 Y 2 15 Y 1
What I want is this result: 我想要的是这个结果:
B C Count -------------- 11 X 1 15 X 1 20 Y 2
Is there any query that can return this result. 是否有任何查询可以返回此结果。 Server is SQL Server 2005. 服务器是SQL Server 2005。
I like to work in steps: first get rid of duplicate A records, then group. 我喜欢分步骤工作:首先清除重复的A记录,然后进行分组。 Not the most efficient, but it works on your example. 不是最有效的方法,但是它适用于您的示例。
with t1 as (
select A, max(B) as B, C
from YourTable
group by A, C
)
select count(A) as CountA, B, C
from t1
group by B, C
I have actually tested this: 我实际上已经测试过:
SELECT
MAX( B ) AS B,
C,
Count
FROM
(
SELECT
B, C, COUNT(DISTINCT A) AS Count
FROM
t
GROUP BY
B, C
) X
GROUP BY C, Count
and it gives me: 它给了我:
B C Count
---- ---- --------
15 X 1
15 y 1
20 y 2
Check this out. 看一下这个。 This should work in Oracle, although I haven't tested it; 尽管我尚未对其进行测试,但这应该可以在Oracle中使用。
select count(a), BB, CC from
(
select a, max(B) BB, Max(C) CC
from yourtable
group by a
)
group by BB,CC
WITH cteA AS
(
SELECT
A, C,
MAX(B) OVER(PARTITION BY A, C) [Max]
FROM T1
)
SELECT
[Max] AS B, C,
COUNT(DISTINCT A) AS [Count]
FROM cteA
GROUP BY C, [Max];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.