将DISTINCT与ORDER BY子句一起使用

时间:2015-04-30 05:44:18

标签: sql-server select sql-order-by distinct

我想改变以下存储过程

ALTER Procedure [dbo].[spEGCRedemptionReportForMHR]  

@DateTo datetime,
@DateFrom datetime,
@MerchantID varchar(11),
@Pan varchar(16)
As
Set @DateTo = @DateTo +1
Select Distinct
Convert(varchar(50),pt.TransactionDate,103) 'TransactionDate',
m.MerchantName1 MerchantName,
m.MerchantAddress Location,
m.MerchantID,
pt.TerminalID,
pt.batchnumber 'Batch #',
pt.SequenceNumber 'Receipt #',
pt.PAN 'Card Number',
c.EmbossName 'Card Holder Name',

Convert(Decimal(10,2),Case when pt.TransactionTypeID=2 then (pt.TotalAmount) end) As 'Points Redeemed',
Convert(Decimal(10,2),Case when pt.TransactionTypeID=2 then (((pt.TotalAmount)/(cc.usdconversionrate))/2) end) as 'Total Payment Amount (AED)', --/cc.USDConversionRate end) As 'Total Amount in AED',
Convert(Decimal(10,2),Case when pt.TransactionTypeID=2 then (((pt.TotalAmount)/(cc.usdconversionrate))/2) -15 end) as 'Total loaded Amount (AED)',
3.00 as 'Procco Share',
Convert(Decimal(10,2),Case when pt.TransactionTypeID=2 then (((pt.TotalAmount)/(cc.usdconversionrate))/2) - 3 end) as 'Settlement Amount'

from POS_Transactions pt
inner join Terminal t on t.TerminalID=pt.TerminalID
inner join Merchant m on m.MerchantID=t.MerchantID
inner join Card c on c.EmbossLine=pt.PAN
inner join Share s on s.MerchantID=m.MerchantID,Currency cc
where IsEmaar =1 and
cc.CurrencyCode='AED'
--and m.isemaarmerchant = 1
and (m.MerchantID=@MerchantID or @MerchantID='-999')
and (pt.TransactionDate>=@datefrom and pt.TransactionDate<=@dateto)
and (pt.PAN=@Pan or @Pan ='-999')
order by pt.TransactionDate

但每次我尝试执行它时都会抛出错误

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

我已经在我的选择中使用了pt.TransactionDate,但仍然要求我包含它,因为它在我的order by子句中。我的查询可能有什么问题?

4 个答案:

答案 0 :(得分:1)

尝试:

ORDER BY 'TransactionDate'

答案 1 :(得分:0)

错误没有帮助,但ughai的评论是正确的。引擎特别关于如何在SELECT语句中修改列,并且确切的形式必须包含在“ORDER BY”中。

出于输出原因连接列时遇到了这种情况,并且它变得很难看。

你必须

ORDER BY Convert(varchar(50),pt.TransactionDate,103)

答案 2 :(得分:0)

如果您使用GROUP BY而不是DISTINCT来消除重复项,那么您可以包括分组字段,无论它们是否在选择列表中。缺点是您必须列出所有所使用的列,但这样做。

GROUP BY 
pt.TransactionDate,
m.MerchantName1,
m.MerchantAddress ,
m.MerchantID,
pt.TerminalID,
pt.batchnumber,
pt.SequenceNumber,
pt.PAN ,
c.EmbossName,
pt.TransactionTypeID,
pt.TotalAmount,
cc.usdconversionrate
ORDER BY pt.TransactionDate

答案 3 :(得分:-1)

是的,列pt.TransactionDate出现在SELECT中,但在CONVERT函数内部如下所示:

CONVERT(VARCHAR(50), pt.TransactionDate, 103) 'TransactionDate',

将pt.TransactionDate自身添加为额外列,如下所示:

  ...     
  SELECT DISTINCT
    CONVERT(VARCHAR(50), pt.TransactionDate, 103) 'TransactionDate',
    pt.TransactionDate, -- <-- here
    m.MerchantName1 MerchantName,
    m.MerchantAddress Location,
    m.MerchantID,
    pt.TerminalID,
  ....