Closed. This question needs to be more focused。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,使其仅通过editing this post专注于一个问题。
                        
                        在10个月前关闭。
                                                                                            
                
        
我有下表,其中包含以下项目

CREATE TABLE IF NOT EXISTS `lib_transactions` (
  `transaction_id` int(11) NOT NULL,
  `person` varchar(60) NOT NULL,
  `isbn` varchar(20) NOT NULL,
  `action` varchar(20) NOT NULL,
  `timestamp` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=205 DEFAULT CHARSET=utf8;

--
-- Dumping data for table `lib_transactions`
--

INSERT INTO `lib_transactions` (`transaction_id`, `person`, `isbn`, `action`, `timestamp`) VALUES
(186, '1', '99-9263-544-4', 'check-out', 1483228800),
(187, '2', '99-9263-544-5', 'check-out', 1483229100),
(188, '1', '99-9263-544-4', 'check-in', 1483315200),
(189, '2', '99-9263-544-5', 'check-in', 1483661100),
(190, '3', '99-9263-544-4', 'check-out', 1483747500),
(191, '2', '99-9263-544-6', 'check-out', 1483833900),
(192, '2', '99-9263-544-6', 'check-in', 1483920300),
(193, '3', '99-9263-544-7', 'check-out', 1484006700),
(194, '3', '99-9263-544-8', 'check-out', 1484100300),
(195, '3', '99-9263-544-7', 'check-in', 1484453100),
(196, '3', '99-9263-544-8', 'check-in', 1484460300),
(197, '4', '99-9263-544-7', 'check-out', 1484553900),
(198, '4', '99-9263-544-8', 'check-out', 1484611500),
(199, '4', '99-9263-544-7', 'check-in', 1484705100),
(200, '4', '99-9263-543-8', 'check-in', 1484798700),
(201, '5', '99-9263-543-1', 'check-out', 1484798700),
(202, '5', '99-9263-544-2', 'check-out', 1484798700),
(203, '5', '99-9263-542-3', 'check-out', 1484798700),
(204, '5', '99-9263-541-4', 'check-out', 1484798700);


我如何实现以下查询:

-哪个人目前拥有最多的图书?

最佳答案

您可以按人分组,获得结帐数减去签入数(使用case when),然后按该结果的降序排列。然后只保留前1个结果:

select   person,
         sum(case action when 'check-out' then 1 when 'check-in' then -1 else 0 end) checked_out
from     lib_transactions
group by person
order by checked_out desc
limit    1


根据您的样本数据,第5个人将成为获胜者,并签出了4本书。

关于mysql - MySQL查询:找到图书馆结账最多的人? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55211134/

10-13 02:52