我尝试设置左连接,但是当我使用一列group by
并选择多列时,我遇到了SQL错误。
这是我的疑问:
SELECT
b.ClientCode,
b.LastName, b.FirstName,
b."Id" AS IdClient,
c.CaseDate,
b.Gender,
b.BirthDate
FROM
dbo.Clients b
LEFT JOIN
dbo.ClientCases c ON c.ClientCode = b.ClientCode
WHERE
b.ClientCode LIKE '%1%'
AND DATEDIFF(DAY, '01/06/2017', c.CaseDate) >= 0
AND DATEDIFF(DAY, '05/06/2017', c.CaseDate) <= 0
GROUP BY
b.ClientCode
ORDER BY
b.ClientCode
当我写这样的查询时:
SELECT
b.ClientCode,
b.LastName, b.FirstName,
b."Id" AS IdClient,
c.CaseDate,
b.Gender,
b.BirthDate
FROM
dbo.Clients b
LEFT JOIN
dbo.ClientCases c ON c.ClientCode = b.ClientCode
WHERE
b.ClientCode LIKE '%1%'
AND DATEDIFF(DAY, '01/06/2017', c.CaseDate) >= 0
AND DATEDIFF(DAY, '05/06/2017', c.CaseDate) <= 0
GROUP BY
b.ClientCode, b.LastName, b.FirstName, b."Id",
b.Gender, b.BirthDate, c.CaseDate
ORDER BY
b.ClientCode
它正在运作 - 但它会返回重复的ClientCode
...
我该怎么办?
答案 0 :(得分:4)
由于GROUP BY,您需要为其他列添加MAX(或MIN或其他聚合函数)。否则它不知道你想要的值。
SELECT b.ClientCode
,MAX(b.LastName)
,MAX(b.FirstName)
,MAX(b."Id") AS IdClient
,MAX(c.CaseDate)
,MAX(b.Gender)
,MAX(b.BirthDate)
FROM dbo.Clients b
LEFT JOIN dbo.ClientCases c ON c.ClientCode = b.ClientCode
WHERE b.ClientCode LIKE '%1%'
AND DATEDIFF(day, '01/06/2017', c.CaseDate) >= 0
AND DATEDIFF(day, '05/06/2017', c.CaseDate) <= 0
GROUP BY b.ClientCode
ORDER BY b.ClientCode
我怀疑你得到的错误是:
Msg 8120, Level 16, State 1, Line 1
Column 'blah blah' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.