【问题标题】:DISTINCT value from stored procedure来自存储过程的 DISTINCT 值
【发布时间】:2016-09-07 16:15:45
【问题描述】:
CREATE PROCEDURE [dbo].[GetIdleCustomerlist](
@num_months Int
)

AS
BEGIN

SELECT DISTINCT
    cust.cust_code as cust_code ,
    cust.name as cust_name,
    MAX (invoice.created_date) as Last_invoice_date             

    FROM [dbo].[customer] cust LEFT JOIN  [dbo].[crm_invoice_header] invoice on cust.cust_code = invoice.cust_code

    GROUP BY cust.cust_code ,cust.name,invoice.created_date

    HAVING (( MAX (invoice.created_date)< DATEADD(MONTH, -@num_months ,GETDATE())) OR invoice.created_date IS NULL)

    ORDER BY CAST (cust.cust_code AS int) ASC

END

我想删除重复的客户代码,但 DISTINCT 关键字给了我这个错误。

消息 145,级别 15,状态 1,过程 GetIdleCustomerlist,第 21 行 如果指定了 SELECT DISTINCT,则 ORDER BY 项必须出现在选择列表中。

【问题讨论】:

    标签: sql sql-server stored-procedures


    【解决方案1】:

    试试这个版本的查询:

    SELECT cust.cust_code as cust_code, cust.name as cust_name,
          MAX(invoice.created_date) as Last_invoice_date             
    FROM [dbo].[customer] cust LEFT JOIN
         [dbo].[crm_invoice_header] invoice
         on cust.cust_code = invoice.cust_code
    GROUP BY cust.cust_code, cust.name
    HAVING (( MAX (invoice.created_date) < DATEADD(MONTH, -@num_months, GETDATE())) OR MAX(invoice.created_date) IS NULL)
    ORDER BY CAST(cust.cust_code AS int) ASC;
    

    distinct 不是必需的,您需要从GROUP BY 中删除日期。

    【讨论】:

    • 删除日期时,它给我错误“消息 8121,级别 16,状态 1,第 7 行列 'dbo.crm_invoice_header.created_date' 在 HAVING 子句中无效,因为它不包含在聚合函数或 GROUP BY 子句。"
    • @Amila 。 . .你只需要使用MAX(invoice.created_date)
    【解决方案2】:

    删除DISTINCT并删除GROUP BY子句中的invoice.created_date

    SELECT
        cust.cust_code AS cust_code,
        cust.name AS cust_name,
        MAX(invoice.created_date) AS Last_invoice_date      
    FROM dbo.customer cust
    LEFT JOIN dbo.crm_invoice_header invoice
        ON cust.cust_code = invoice.cust_code
    WHERE
        invoice.created_date < DATEADD(MONTH, -@num_months, GETDATE())
        OR invoice.created_date IS NULL
    GROUP BY
        cust.cust_code, cust.name
    ORDER BY
        ORDER BY CAST(cust.cust_code AS INT)
    

    您也可以将HAVING中的条件移动到WHERE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 2023-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2017-03-02
      相关资源
      最近更新 更多