如何选择和计算表中的行范围

时间:2015-06-17 23:08:17

标签: mysql sql

我有一个名为projects的表,其中有一个名为projects-bug的列(存储值从0到2000)。表中存储了大约2000行,我需要获取COUNT个项目像4个范围一样:

0 - 500
501 - 1000
1001 - 1500
1501 - 2000

以某种方式显示每个范围中有多少个项目? 如果可以在单行SQL中使用,请告诉我吗?以及如何做到这一点?

4 个答案:

答案 0 :(得分:1)

select sum(`project-bug` between 0 and 500) as 0_500,
       sum(`project-bug` between 501 and 1000) as 501_1000,
       sum(`project-bug` between 1001 and 1500) as 1001_1500,
       sum(`project-bug` between 1501 and 2000) as 1501_2000
from projects

答案 1 :(得分:1)

如果您使用@IBAction func setPicture(sender: UIButton) { var imagePicker: UIImagePickerController = UIImagePickerController() imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary imagePicker.delegate = self let profileImage: PFFile = user["profileImage"] as! PFFile profileImage.getDataInBackgroundWithBlock { (imageData: NSData?, error: NSError?) -> Void in if error == nil { let image: UIImage = UIImage(data: imageData!)! self.profileImageView.image = image } } self.presentViewController(imagePicker, animated: true, completion: nil) } 函数

尝试以下内容,该怎么办?
SUM()

答案 2 :(得分:0)

如果要为每个计数返回单独的行,可以执行以下操作:

  SELECT CONCAT(q.lo,' - ',q.hi)  AS range_
       , COUNT(p.`projects-bug`)  AS count_
    FROM ( SELECT 0 AS lo, 500 AS hi
           UNION ALL SELECT 501, 1000 
           UNION ALL SELECT 1001, 1500
           UNION ALL SELECT 1501, 2000
         ) q
    JOIN projects p
      ON p.`projects-bug` BETWEEN q.lo AND q.hi  
   GROUP BY q.lo, q.hi

答案 3 :(得分:0)

SELECT [blahblah] as calculatedRangeNum
     , CONCAT(MIN(id), '-', MAX(id)) AS idSpan  -- not necessary of course, merely for confirmation
     , COUNT(1) AS rowsInSpan
FROM someTable
GROUP BY calculatedRangeNum
;

你的榜样的[blahblah]可能是

(id-1) DIV 500

或(更准确地说)

IF(id BETWEEN 0 AND 500, 1
  , IF(id BETWEEN 501 AND 1000, 2
  , [etc....]))

编辑:您甚至可以添加一个WHERE子句,这样您就可以做一些事情,比如只获取活动/过期/无论项目的数量。