如何计算许多字段(MySql)

时间:2018-07-23 13:18:56

标签: mysql sql

我有一张看起来像下面的桌子,希望对所有预订进行计数,其中包括每周所有客人的数量。有30个来宾字段:

locations

| Field        | Type       |
| ------------ | ---------- |
| location     | text       |
| day_number   | int(11)    |
| month_number | int(11)    |
| year         | text       |
| week_number  | tinyint(4) |
| start        | datetime   |
| end          | datetime   |
| guest_1      | text       |
| guest_2      | text       |
| …            |            |
| guest_30     | text       |

我正在使用:

select locaton, count(*) AS `Number of bookings per week`, week_number, 
month_number, `month`
FROM locations
GROUP BY location, week_number;

那让我:

| location     | ...Bookings | week_number | month_number | January  |
| ------------ | ----------- | ----------- | ------------ | -------- |
| Location One | 3           | 2           | 1            | January  |
| Location One | 5           | 3           | 1            | January  |
| Location One | 2           | 4           | 1            | January  |
| Location One | 2           | 5           | 2            | February |
| Location One | 5           | 6           | 2            | February |
| Location One | 1           | 7           | 2            | February |
| Location One | 3           | 8           | 2            | February |

有很多位置。

如何在查询的每周和位置的30个访客字段中合并访客数量

谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

只需对每种组合的来宾计数,然后对这些计数求和

SELECT location,week_number,month_number,SUM(
(guest_1 <> "") +
(guest_2 <> "") +
(guest_3 <> "") +
....
(guest_30 <> "")
) AS num_guests
FROM locations
GROUP BY location,week_number,month_number

答案 1 :(得分:0)

这很困难,因为此表未规范化。 我认为这是可能的,请重新创建此解决方案并使用 LOCATION 中的外键创建新表 GUEST

下一步是创建子查询,例如:

let obj = await superagent
.post(url)
.type('form')
.send(*****would like to examine request object here or in serialize****)
.serialize(*****does not fire*****)
.catch(*****works fine****)

这将是更好的解决方法,因为在这种情况下,您可以添加更多的来宾而无需更改逻辑表。 根据您的情况,您始终要分别检查每一列。