存储过程中的DISTINCT值

时间:2016-05-12 03:07:35

标签: sql sql-server stored-procedures

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关键字给了我这个错误。

Msg 145,Level 15,State 1,Procedure GetIdleCustomerlist,Line 21 如果指定了SELECT DISTINCT,则ORDER BY项必须出现在选择列表中。

2 个答案:

答案 0 :(得分:2)

尝试此版本的查询:

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中删除日期。

答案 1 :(得分:2)

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

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