6

我对 SQL Server 很陌生,所以我现在道歉。

我有一个表,我想 GroupByfield1并返回该字段field2中关联计数最高的记录。counted我通常会在 MS ACCESS 中使用 2 个查询来执行此操作,第一个查询以降序返回数据,第二个查询使用 First() 函数选择第一条记录,如下所示:-

查询 1

SELECT t.field1, t.field2, Count(t.counted) AS count1
FROM Table1 AS t
WHERE (((t.counted)=2))
GROUP BY t.field1, t.field2
ORDER BY t.field1, Count(t.counted) DESC;

查询 2(基于上面的查询 1)

SELECT q.field1, First(q.field2) AS firstoffield2
FROM q
GROUP BY q.field1;

我正在寻找的 SOURCE DATA 和查询结果

我很难在 SQL Server 2008 查询中完成与上述相同的结果。有人可以帮忙吗?(请提供我需要使用的准确 SQL)。

这是数据的子集和结果示例:-

表格1

field1 ¦ field2 ¦ counted
10     ¦ 20     ¦ 2
10     ¦ 30     ¦ 2
10     ¦ 20     ¦ 2
20     ¦ 30     ¦ 0
20     ¦ 40     ¦ 0
20     ¦ 50     ¦ 1
20     ¦ 50     ¦ 2
20     ¦ 60     ¦ 1

Query1 results (groups by field1, counts where "counted" field record is "2")

field1 ¦ field2 ¦ count1
10     ¦ 20     ¦ 2
10     ¦ 30     ¦ 1
20     ¦ 50     ¦ 1

Query 2 resuls (the output I want to get from SQL)

field1 ¦ firstoffield2
10     ¦ 20
20     ¦ 50

I hope that helps a bit, thanks guys.

4

3 回答 3

6
WITH
  q AS
(
  Put your query one here
)
,
  sequenced AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY field1 ORDER BY count1 DESC) AS sequence_id,
    *
  FROM
    q
)
SELECT
  *
FROM
  sequenced
WHERE
  sequence_id = 1

To change this to LAST() change the order direction in the ROW_NUMBER() function.

于 2012-10-16T17:10:48.153 回答
1

This isn't the most elegant query I've ever written, but how about something like this:

SELECT qSource.Field1, qSource.Field2
FROM (SELECT Field1, Field2, COUNT(Counted) AS Count1
    FROM dbo.Table1
    WHERE Counted = 2
    GROUP BY Field1, Field2)qSource
INNER JOIN (SELECT q.Field1,MAX(q.Count1) AS HighestCount
    FROM (SELECT Field1, Field2, COUNT(Counted) AS Count1
        FROM dbo.Table1
        WHERE Counted = 2
        GROUP BY Field1, Field2) q
    GROUP BY q.Field1) qHighest
ON qSource.Field1 = qHighest.Field1
AND qSource.Count1 = qHighest.HighestCount
ORDER BY qSource.Field1
于 2012-10-16T17:12:13.533 回答
0

I was looking for the same thing and didn't like the complicated solutions, so I kept looking and found this:

https://www.sqlservercentral.com/forums/topic/t-sql-equivalent-to-ms-access-first-function

Use "Top 1"

Select Top 1 SomeColumn From SomeTable Order By

This is really nice because you have added functionality of a complex ORDER BY to get exactly which one you want If there are multiple firsts

于 2021-03-20T03:36:17.827 回答