聚合 SQL 函数以从每个分组中仅获取一个

发布于 2024-09-09 04:42:52 字数 490 浏览 2 评论 0原文

我有一个表,需要对 SQL-Server 2000 中的许多字段进行规范化。 它包含 2 个字段,我用它们来提出规范定义的不同组合。 ID 和费率:有多行相同的 ID 和费率

我首先通过对 ID 和费率组合进行分组来创建临时表。

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

现在我使用 Distinct 来仅查找唯一的组合。因此,我将有多个 ID 组共享相同的 Total 和 IDCounts

SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp

现在我的问题是如何将单个 ID 连接回 IDCounts 和 Total 的不同分组并将其放入新表中?只要我使用同一组中的 ID,组中的哪一个 ID 并不重要。

I have a table that I need to normalize with many fields In SQL-Server 2000.
It contains 2 fields which I'm using to come up with distinct combination as defined by the specs.
ID and Rate: there are multiple rows of same IDs and Rates

I first created a temp table by grouping the IDs and Rates combination.

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

Now I use Distinct to find only the unique combinations. So i'll have multiple ID groups sharing same Total and IDCounts

SELECT DISTINCT Total, IDCounts
INTO #uniques
FROM #Temp

Now my question is how to join a single ID back to that distinct grouping of IDCounts and Total and put that into a new table? It doesn't matter which one of the IDs in the groups as long as I use one from the same grouping.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

¢蛋碎的人ぎ生 2024-09-16 04:42:52

保留临时表(尽管这可以在单个查询中完成):

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

SELECT Total, IDCounts, MIN(ID) AS SomeID
INTO #uniques
FROM #Temp
GROUP BY Total, IDCounts

Keeping your temp tables (although this could all be done in a single query):

SELECT ID, Count(*) AS IDCounts, SUM(RATE) As Total 
INTO #Temp
GROUP BY ID

SELECT Total, IDCounts, MIN(ID) AS SomeID
INTO #uniques
FROM #Temp
GROUP BY Total, IDCounts
千笙结 2024-09-16 04:42:52

将“Min(ID) AS FirstID”添加到#uniques 中的选择中。

Add "Min(ID) AS FirstID" to the select into #uniques.

蘑菇王子 2024-09-16 04:42:52

尝试这样的事情:

SELECT MAX(ID) AS Id, Count(*) AS IDCounts, SUM(RATE) As Total 
FROM SOMETABLE
GROUP BY IDCounts, Total

Try something like this:

SELECT MAX(ID) AS Id, Count(*) AS IDCounts, SUM(RATE) As Total 
FROM SOMETABLE
GROUP BY IDCounts, Total
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文