如何使用Group By,但保留列中的所有其他值(在mysqli中)

时间:2018-04-05 18:35:35

标签: php sql mysqli

是否可以使用分组依据,但保留列中的所有其他关联值?

month | date     | location
---------------------------
april  | 4/11/18 | US
april  | 4/16/18 | US
may    | 5/14/18 | Canada
june   | 6/05/18 | Canada
june   | 6/30/18 | US 

基本上,我想显示月份的不同值,但要匹配相应月份下方的日期,并保留其他值。

april: 4/11/18 (US), 4/16/18 (US)
may: 5/14/18 (Canada)
june: 6/05/18 (Canada), 6/30/18 (US)

以下是我使用的代码:

$query = ("SELECT * FROM events GROUP BY month");

这只是显示了不同的月份。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

使用switch to

GROUP_CONCAT

def merge_close_pts(pts, rad=5): # pts is a numpy array of size mx2 where each row is ( xy )
pts = np.float32(pts) # avoid issues with ints

# iteratively make points that are close to each other get closer ( robust to clouds of multiple close pts merge )
pts_to_merge = (np.sqrt(np.power(pts[:, 0].reshape(-1, 1) - pts[:, 0].reshape(1,-1),2) + \
                   np.power(pts[:, 1].reshape(-1, 1) - pts[:, 1].reshape(1, -1), 2))) <= rad

for _ in range(5):
    for pt_ind in range(pts.shape[0]):
        pts[pt_ind,:] = pts[pts_to_merge[pt_ind, :], :].reshape(-1, 2).mean(axis=0)

#now keep only one pts from each group. 
pts_to_merge = ((np.sqrt(np.power(pts[:, 0].reshape(-1, 1) - pts[:, 0].reshape(1, -1), 2) + \
                        np.power(pts[:, 1].reshape(-1, 1) - pts[:, 1].reshape(1, -1), 2))) <= rad) * \
               (np.eye(pts.shape[0])== 0)


for pt_ind in range(pts.shape[0]):
    if (pts[pt_ind,:] == 0).all() == False:
        inds_to_erase = pts_to_merge[pt_ind, :]
        pts[inds_to_erase, :] = 0


return pts[(pts==0).all() == False, :]

<强>输出

 SELECT month,
        GROUP_CONCAT( date, '(', location, ')' ) as data
 FROM YourTable
 GROUP BY month