admin

在选择列表中,列“ dbo.User.FB_UserId”无效,因为该列既不包含在聚合函数中,也不包含在GROUP BY子句中

sql

我在这里多次看到此错误消息,但是我没有从中解决我的特定问题(可能是因为我不是sql专家),所以请原谅我将问题发布到同一位置错误。

这是我要执行的查询:

SELECT DISTINCT U.FB_UserId
 , U.Id AS GameUserID
 , U.FbLocale
 , U.FbGender
 , U.FbBirthday
 , U.RegistredAt
 , U.LoginCount
 , U.PlayCount
 , U.MarketGroupId

    , (SELECT COUNT(C.PriceFbCredits)
    WHERE UserID = U.Id) AS Payments

    , (SELECT SUM(CASE WHEN C.PriceFbCredits = 13 THEN 1 END)
    WHERE UserID = U.Id) AS P13

    , (SELECT SUM(CASE WHEN C.PriceFbCredits = 52 THEN 1 END)
    WHERE UserID = U.Id) AS P52

    , (SELECT SUM(CASE WHEN C.PriceFbCredits = 130 THEN 1 END)
    WHERE UserID = U.Id) AS P130

FROM [dbo].[User] AS U WITH (NOLOCK) INNER JOIN [dbo].[FbCreditsCallback] AS C WITH (NOLOCK) ON C.UserId = U.Id

如果这样做,我会收到错误消息。好的,我知道这意味着什么,我有点理解该怎么做,但是我认为如果这样做不会给我想要的结果…我想要一些特定数据userid。一些数据需要加总,一些数据需要计数,并且在结果列表中每个ID应该只出现一次。

现在这是(对我来说)有趣的事情。如果我这样编写内部的SELECT查询,则不会收到错误消息。但是我不知道返回的数据是否正确:

, (SELECT COUNT(PriceFbCredits)
FROM [dbo].[FbCreditsCallback]
WHERE UserID = U.Id) AS Payments

…老实说,我有点迷路了,我希望能有所帮助。


阅读 242

收藏
2021-06-07

共1个答案

admin

在下面,SQL Server当您使用分组功能来生成聚合函数时,您将看到正确的语法。

你的WHERE UserID = U.Id,因为你正在为它的一部分是没有必要的INNER JOIN条款。

因此,请尝试以下操作:

SELECT DISTINCT U.FB_UserId
 , U.Id AS GameUserID
 , U.FbLocale
 , U.FbGender
 , U.FbBirthday
 , U.RegistredAt
 , U.LoginCount
 , U.PlayCount
 , U.MarketGroupId
 , COUNT(*)  AS Payments
 , SUM(CASE WHEN C.PriceFbCredits = 13 THEN 1 ELSE 0 END) AS P13
 , SUM(CASE WHEN C.PriceFbCredits = 52 THEN 1 ELSE 0 END) AS P52
 , SUM(CASE WHEN C.PriceFbCredits = 130 THEN 1 ELSE 0 END) AS P130

FROM [dbo].[User] AS U WITH (NOLOCK) 
INNER JOIN [dbo].[FbCreditsCallback] AS C WITH (NOLOCK) ON C.UserId = U.Id
GROUP BY U.FB_UserId
 , U.Id 
 , U.FbLocale
 , U.FbGender
 , U.FbBirthday
 , U.RegistredAt
 , U.LoginCount
 , U.PlayCount
 , U.MarketGroupId

如你所写

我不是SQL专家

从现在开始,避免使用WITH(NOLOCK),就像您询问 SELECT [data] FROM [TABLE] WITH(I really, reallydon't care if it is accurate or not)

在某些情况下有这样做的理由,但是如果您是初学者,SQL我会怀疑您是否处于这种情况。

2021-06-07