1

Assume the following:

CREATE TABLE #Testing
(
      [id] [int] IDENTITY(1,1) NOT NULL,
      [store_id] [varchar](3) NULL,
      [sku] [varchar](14) NULL,
      [qty] [bigint] NULL,
      [http_action] [varchar](20) NULL
)

INSERT INTO #Testing (store_id, sku, qty, http_action)
SELECT '001','123456',1,'POST'
UNION ALL
SELECT '002','123456',1,'POST'
UNION ALL
SELECT '002','123456',1,'DELETE'
UNION ALL
SELECT '001','223456',5,'DELETE'

What’s a single query that you could run to return the minimum [id] for each [http_action]? Something like:

MIN_DELETE  MIN_POST
3           1

GO
4

2 回答 2

4

您可以使用带有CASE表达式的聚合函数来获取min(id)for each http_action

select 
  min(case when http_action='DELETE' then id end) Min_Delete,
  min(case when http_action='POST' then id end) Min_Post
from #testing;

请参阅SQL Fiddle with Demo

上面的查询将min(id)值放入单独的列中,如果您希望它们成行,那么您可以使用:

select min(id) id,
  http_action
from #testing
group by http_action;

请参阅带有演示的 SQL Fiddle

于 2013-05-01T18:16:28.693 回答
0

另一种解决方法是在 http_action 上使用简单的 group by。但是,您将获得每个操作的一行:

select http_action, MIN(id) min_id from #Testing group by http_action

输出:

http_action  min_id
DELETE         3
POST           1
于 2013-05-02T08:33:19.997 回答