如果存在具有多个值的事务,则SQL Server返回文本

时间:2015-08-31 15:49:17

标签: sql-server

我正在运行销售查询,每个交易可能有多个订单号。如果是这种情况,我希望查询在列中返回单词“Multiple”,如果它只有一个订单,则返回订单#。

SELECT Distinct TOP 10000 [Store Number]
  ,[Store Name]
  ,[Register Sales Posting Date]
  ,[Transaction Date]
  ,[Register ID]
  ,[Transaction ID]
  ,[Net Sales]
  ,[Tax Exempt Sales]
  ,[Markdown]
  ,[Tax Amount]
  ,[Gross Sales]
  ,[Tax Exempt ID]
  ,CASE
     WHEN COUNT([Customer Order Number])>'1' THEN 'Multiple'
     ELSE[Customer Order Number]
   END
FROM [PropertyTax].[dbo].[SQLAExport]
WHERE [Store Number] = '4920'
  AND [Transaction Date] = '1/14/2011'
GROUP BY 
       [Store Number]
      ,[Store Name]
      ,[Register Sales Posting Date]
      ,[Transaction Date]
      ,[Register ID]
      ,[Transaction ID]
      ,[Net Sales]
      ,[Tax Exempt Sales]
      ,[Markdown]
      ,[Tax Amount]
      ,[Gross Sales]
      ,[Tax Exempt ID]
      ,[Customer Order Number]

1 个答案:

答案 0 :(得分:3)

如果您使用的是SQL Server 2012+,则可以使用count() over (partition by ...)。如果在较低版本上,您可以使用cross apply获取每笔交易的订单数量(或者您未按分区划分)(有关这两种技术的示例,请参阅此SQL Fiddle

尝试删除group by并更改case表达式以使用窗口计数(在此查询中我假设[Transaction ID]是要分区的东西(指定一个组),如果它不是你可能要改变它)。

也许这就是你要找的东西:

SELECT TOP 10000 
   [Store Number]
  ,[Store Name]
  ,[Register Sales Posting Date]
  ,[Transaction Date]
  ,[Register ID]
  ,[Transaction ID]
  ,[Net Sales]
  ,[Tax Exempt Sales]
  ,[Markdown]
  ,[Tax Amount]
  ,[Gross Sales]
  ,[Tax Exempt ID]
  , CASE WHEN COUNT([Customer Order Number]) OVER (PARTITION BY [Transaction ID]) > 1 
         THEN 'Multiple'
        ELSE [Customer Order Number] 
    END -- if [Customer Order Number] is a number and not a char you need to cast it
FROM [PropertyTax].[dbo].[SQLAExport]
WHERE [Store Number] = '4920'   
  AND [Transaction Date] = '1/14/2011'

此外,请注意,使用top n而没有任何order by子句不会给您一个确定性结果,而是随机选择n行(可能看似有序但是不保证是)。使用order by时,请始终加入top