我有以下查询(并尝试了它的很多变体) :
select housedata.housecode, housedata.name, min((pergroup + (perguest * GREATEST((2 - guests_included),0)))) as mincalculated
from housedata
inner join availabilitydata
where housedata.housecode = availabilitydata.housecode
and datediff(departure, arrival) = 7 group by housedata.housecode
这工作正常,但我需要表可用性数据中的更多字段。当我尝试添加这些 MySQL 提示时:
[42000][1055] Expression #4 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'houses.availabilitydata.arrival' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
我可以将该字段添加到分组依据中,但随后我会得到多个结果,因为可用性数据是多行。
如何将其限制为每栋房屋一行,即从中获取 min((pergroup + (perguest * GREATEST((2 - guest_included),0)))) 的行。
表格:
create table availabilitydata
(
arrival date not null,
departure date not null,
housecode varchar(32) not null,
pergroup float null,
pergroupexcldiscount float null,
perguest float null,
guests_included tinyint null,
primary key (housecode, arrival, departure)
);
create table housedata
(
housecode varchar(32) not null
primary key,
name tinytext null
);
数据应如下所示,但添加了日期列:
344323 Wienerwaltz 680.530029296875
434300 Wald 882.7899780273438
943843 Chalet Miquel 630.8300170898438
最佳答案
尝试这样:
select h.housecode
, hh.name
, pergroup + (perguest * GREATEST((2 - guests_included),0)) as mincalculated
-- select any column from a (availabilitydata)
from housedata h
inner join availabilitydata a on a.housecode = h.housecode
where (a.housecode, a.arrival, a.departure) = (
select a2.housecode, a2.arrival, a2.departure
from availabilitydata a2
where a2.housecode = h.housecode
and datediff(a2.departure, a2.arrival) = 7
order by a2.pergroup + (a2.perguest * GREATEST((2 - a2.guests_included),0)) asc
limit 1
)
在相关子查询中,您将获得计算值最小的行的主键(a.housecode, a.arrival, a.departure
)。在外部查询中,您仅选择 availabilitydata
中具有相同主键的行。
请注意,如果两行具有相同的计算最小值,您将同时获得它们。如果您不需要两者,您应该在 ORDER BY 子句中定义您想要的一个(例如,添加完整的主键):
order by a2.pergroup + (a2.perguest * GREATEST((2 - a2.guests_included),0)) asc
, a2.arrival
, a2.departure
更新
上述解决方案似乎表现不佳。但如果您的版本支持窗口函数,您还可以使用以下查询:
select *
from (
select housedata.housecode
, housedata.name
, pergroup + (perguest * GREATEST((2 - guests_included),0)) as mincalculated
, row_number() over (
partition by housedata.housecode
order by pergroup + (perguest * GREATEST((2 - guests_included),0)) asc
) rn
, availabilitydata.arrival
-- select any other column from availabilitydata
from housedata
inner join availabilitydata on housedata.housecode = availabilitydata.housecode
where datediff(departure, arrival) = 7
) x
where rn = 1
关于mysql - 无法使用 group by 查询获取 MySQL 中的某些字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54957834/