我试图运行此SQL语句,但似乎遇到了一个错误状态
Msg 8120,Level 16,State 1,Procedure MemberCountryCarLocation,Line 5
专栏' Country.Country_name'在选择列表中无效,因为 它不包含在聚合函数或GROUP BY中 子句。
代码:
create view MemberCountryCarLocation
(Member_ID, Country_Of_Rental, Home_Addr, Business_Name)
as
select
M.member_Id, C.country_name, A.addr1, B.business_addr
from
Member M, Country C, License L, Addr A, Bz_Addr B
where
M.member_id = A.member_id
and A.country_code = C.Country_code
and B.addr_code = A.addr_code
and M.member_id = 'M%'
group by
M.member_id
答案 0 :(得分:0)
如果您使用group by
,则只能选择分组语句和聚合函数中的列,如sum()
。
因此,您必须删除select
group by
子句中的所有值
select M.member_Id
from Member M, Country C, License L, Addr A, Bz_Addr B
where M.member_id = A.member_id
and A.country_code = C.Country_code
and B.addr_code = A.addr_code
and M.member_id = 'M%'
group by M.member_id
或者您必须将select
子句中的所有值添加到group by:
select M.member_Id, C.country_name, A.addr1, B.business_addr
from Member M, Country C, License L, Addr A, Bz_Addr B
where M.member_id = A.member_id
and A.country_code = C.Country_code
and B.addr_code = A.addr_code
and M.member_id = 'M%'
group by M.member_id, C.country_name, A.addr1, B.business_addr
答案 1 :(得分:0)
在这种情况下,您需要添加 group by 时选择的所有列名。
试试这个:
create view MemberCountryCarLocation
(Member_ID, Country_Of_Rental, Home_Addr, Business_Name)
AS
select M.member_Id, C.country_name, A.addr1, B.business_addr
from Member M, Country C, License L, Addr A, Bz_Addr B
where M.member_id = A.member_id
and A.country_code = C.Country_code
and B.addr_code = A.addr_code
and M.member_id = 'M%'
group by M.member_Id, C.country_name, A.addr1, B.business_addr
答案 2 :(得分:0)
试试这个,从select子句中删除不在
组中的值select M.member_Id
from Member M, Country C, License L, Addr A, Bz_Addr B
where M.member_id = A.member_id
and A.country_code = C.Country_code
and B.addr_code = A.addr_code
and M.member_id = 'M%'
group by M.member_id
阅读分组依据here
答案 3 :(得分:0)
在对查询进行分组时,您只能选择要分组的字段。如果您需要其他字段,则需要在分组中添加它们,或使用聚合来计算要选择的值。
我添加了分组中的其他字段(假设您只从每个成员的每个tablke获得一个值),这允许您选择它们。
您应该使用join
关键字来建立连接,而不是旧方式连接表,因为旧方法已被弃用。
我从查询中排除了表License
,因为您没有将其用于任何事情或将其与任何内容进行匹配,因此它会导致交叉连接,只会复制其他表中的记录。
create view MemberCountryCarLocation
(Member_ID, Country_Of_Rental, Home_Addr, Business_Name)
as
select
M.member_Id,
C.country_name,
A.addr1,
B.business_addr
from
Member M
inner join Addr A on M.member_id = A.member_id
inner join Country C on A.country_code = C.Country_code
inner join Bz_Addr B on B.addr_code = A.addr_code
where
M.member_id = 'M%'
group by
M.member_id,
C.country_name,
A.addr1,
B.business_addr
考虑一下你是否真的需要分组。现在它只是作为distinct
查询工作,除非你有重复的成员,否则不应该这样做。