根据条件对sql中的列求和

时间:2018-06-04 06:31:52

标签: sql

我想根据以下条件对列值求和

 USERID | QUERYID | UPVOTE | DOWNVOTE
   1    | 15      | 1      |  0
   0    | 15      | 0      | -1
   6    | 15      | 0      | -1
   1    | 7       | 1      |  0 
   8    | 7       | 1      |  0

我有兴趣得到这个要求的结果,比如 对于QUERYID = 15,它应该返回-1作为(SUM(UPVOTE)+ SUM(DOWNVOTE)) 对于QUERYID = 7,它应该通过使用与上面相同的逻辑给我2。 我已尝试过以下方式

select (SUM(UPVOTE)+ SUM(DOWNVOTE)) as "TOTAL" from "MY_TABLE" where "QUERYID" in (15, 7)'; 但是给了我所有列的总和以及queryId的综合结果。

4 个答案:

答案 0 :(得分:2)

您需要group by子句才能为queryid的唯一值生成单独的结果:

SELECT   (SUM(upvote) + SUM(downvote)) AS "TOTAL"
FROM     mytable
-- Possibly also add a where clause here if you only want to do this for some queryids
GROUP BY queryid

答案 1 :(得分:1)

使用# data path path_to_depth = './nyu_depth_v2_labeled.mat' # read mat file f = h5py.File(path_to_depth) batch_size=6 pred = np.zeros((6,480,640,3)) gt = np.zeros((6,480,640,1)) for i in range(batch_size): # read 0-th image. original format is [3 x 640 x 480], uint8 img = f['images'][i] # reshape img_ = np.empty([480, 640, 3]) img_[:,:,0] = img[0,:,:].T img_[:,:,1] = img[1,:,:].T img_[:,:,2] = img[2,:,:].T # read corresponding depth (aligned to the image, in-painted) of size [640 x 480], float64 depth = f['depths'][i] depth_ = np.empty([480, 640]) depth_[:,:] = depth[:,:].T pred[i,:,:,:] = img_ gt[i,:,:,0] = depth_ return pred, gt

group by

答案 2 :(得分:1)

你错过了group by子句。

+---+--------+----------------+-----+
|k1 |k3      |k2              |count|
+---+--------+----------------+-----+
|c  |[x2]    |[c3]            |1    |
|a  |[x1, x2]|[b1, e1, c1, a1]|4    |
|a  |[x3]    |[d1]            |1    |
+---+--------+----------------+-----+ 

答案 3 :(得分:1)

select QUERYID, (SUM(UPVOTE)+ SUM(DOWNVOTE)) as "TOTAL" from "MY_TABLE" GROUP BY QUERYID

试试这段代码,让我知道发生了什么