1

无法弄清楚我在这里做错了什么。它说字段 HasNoteDate 无效。如果有日期,我只希望它返回 1,如果没有,我希望它返回 0,并且我希望它分组,以便我可以获得计数和贷款金额的总和。我已经查看了按案例分组的 stackoverflow 答案,但没有一个能帮我解决这个问题。谢谢!

SELECT    dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION, COUNT(*) AS TierRegionCount, 
                      SUM(dbo.LOAN.LOAN_AMT) AS LoanAmtSum, dbo.LOAN.DEAL_STATUS, CASE WHEN dbo.WORKFLOW.NOTE_DATE IS NULL 
                      THEN 0 ELSE 1 END AS HasNoteDate
FROM         dbo.BRKRMAST INNER JOIN
                      dbo.BRKRREF ON dbo.BRKRMAST.BRKRMASTID = dbo.BRKRREF.BRKRMASTID INNER JOIN
                      dbo.LOAN ON dbo.BRKRREF.LoanId = dbo.LOAN.LoanId INNER JOIN
                      dbo.WORKFLOW ON dbo.LOAN.LoanId = dbo.WORKFLOW.LoanId LEFT OUTER JOIN
                      dbo.BDONAMES ON dbo.BRKRMAST.BDONAMESID = dbo.BDONAMES.BDONAMESID
WHERE     (LEN(dbo.BDONAMES.UserID) > 0) AND (dbo.BRKRMAST.Tier > 0) AND (LEN(dbo.BDONAMES.REGION) > 0)
GROUP BY dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION, dbo.LOAN.LOAN_AMT, dbo.LOAN.DEAL_STATUS, HasNoteDate
ORDER BY dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION
4

2 回答 2

2

SQL 查询执行的逻辑不像常见的编程语言那样简单

以下是您的查询的示例执行阶段:

  1. 对中的表执行联接FROM CLAUSE
  2. 执行GROUP BY- 这将导致错误,HasNoteDate目前尚未定义
  3. 履行ORDER BY
  4. 执行SELECT- 仅在此阶段HasNoteDate定义列

所以,你不能HasNoteDate在 GROUP BY 中使用未定义的列,你必须用你的语句替换它(CASE WHEN dbo.WORKFLOW.NOTE_DATE IS NULL THEN 0 ELSE 1 END),然后 sql server 将能够GROUP

于 2013-10-18T22:58:53.207 回答
1
SELECT    dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION, COUNT(*) AS TierRegionCount, 
                      SUM(dbo.LOAN.LOAN_AMT) AS LoanAmtSum, dbo.LOAN.DEAL_STATUS, CASE WHEN dbo.WORKFLOW.NOTE_DATE IS NULL 
                      THEN 0 ELSE 1 END AS HasNoteDate
FROM         dbo.BRKRMAST INNER JOIN
                      dbo.BRKRREF ON dbo.BRKRMAST.BRKRMASTID = dbo.BRKRREF.BRKRMASTID INNER JOIN
                      dbo.LOAN ON dbo.BRKRREF.LoanId = dbo.LOAN.LoanId INNER JOIN
                      dbo.WORKFLOW ON dbo.LOAN.LoanId = dbo.WORKFLOW.LoanId LEFT OUTER JOIN
                      dbo.BDONAMES ON dbo.BRKRMAST.BDONAMESID = dbo.BDONAMES.BDONAMESID
WHERE     (LEN(dbo.BDONAMES.UserID) > 0) AND (dbo.BRKRMAST.Tier > 0) AND (LEN(dbo.BDONAMES.REGION) > 0)
GROUP BY dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION, dbo.LOAN.DEAL_STATUS, CASE WHEN dbo.WORKFLOW.NOTE_DATE IS NULL 
                                                                                                        THEN 0 ELSE 1 END
ORDER BY dbo.BDONAMES.UserID, dbo.BRKRMAST.Tier, dbo.BDONAMES.REGION

完全按照您在 select 语句中定义的方式使用组中的列,否则 SQL 服务器会尝试将其与在 SELECT 语句中找不到的字段进行 GROUP 并引发错误。

于 2013-10-18T23:13:36.037 回答