具有group by和条件的复杂SQL查询

时间:2015-10-20 08:20:57

标签: mysql sql

假设我有以下表格测试:

------------------------------
id | active| record
------------------------------
3  | O     | 2015-10-16
3  | O     | 2015-10-15
3  | N     | 2015-10-14
4  | N     | 2015-10-15
4  | O     | 2015-10-14

我想在表格上对表格进行更新:
- 列激活='O'不止一次的id - 在具有active ='O'不止一次的这些行中,更新应将active的值更改为'N',但max(record)除外,它将保持active ='O'。

在我的示例中,多次激活列='O'的id为id = 3.

id |active | record
------------------------------
3  | O     | 2015-10-16
3  | O     | 2015-10-15
3  | N     | 2015-10-14

我希望得到这样的结果:

id |active | record
------------------------------
3  | O     | 2015-10-16
3  | N     | 2015-10-15
3  | N     | 2015-10-14

我尝试了这个查询,但是出现了错误:

update test as t1,
(select id
from test
where active = 'O'
group by id
having count(*) > 1) as t2
set t1.actif = 'N'
where t1.record != max(t2.record);

提前致谢!

2 个答案:

答案 0 :(得分:0)

鉴于此样本数据:

CREATE TABLE t
    (`id` int, `active` varchar(1), `record` date)
;

INSERT INTO t
    (`id`, `active`, `record`)
VALUES
    (3, 'O', '2015-10-16'),
    (3, 'O', '2015-10-15'),
    (3, 'N', '2015-10-14'),
    (4, 'N', '2015-10-15'),
    (4, 'O', '2015-10-14')
;

此查询

UPDATE 
t
JOIN (
  SELECT 
  id, MAX(record) AS max_record
  FROM 
  t
  WHERE active = 'O'
  GROUP BY id
  HAVING COUNT(*) > 1
) sq ON t.id = sq.id
SET t.active = IF(t.record = sq.max_record, 'O', 'N');

产生这个结果:

+------+--------+------------+
| id   | active | record     |
+------+--------+------------+
|    3 | O      | 2015-10-16 |
|    3 | N      | 2015-10-15 |
|    3 | N      | 2015-10-14 |
|    4 | N      | 2015-10-15 |
|    4 | O      | 2015-10-14 |
+------+--------+------------+

答案 1 :(得分:0)

你可以尝试这样的事吗

select ID, 
count(*) Counted, 
max(record) record 
into #TempTable from Table
where Active = 'O'
group by ID

Update tab
set tab.Active = 'N'
from Table tab
join #tempTable temp on tab.ID = temp.ID
where temp.Counted > 1 and 
tab.record != temp.record

drop table #tempTable

基本上,你只是在将ID和最大记录抓取到临时表中时计算Os,然后你进行更新,这段代码也可能需要一些更改,因为我只是看了一眼指向你的方向我会这样做