如何通过CASE语句中的值进行搜索?

时间:2015-02-25 15:26:57

标签: sql sql-server

我添加了一个CASE语句来获取将在报告中显示的“发票状态”的值。我现在希望能够通过报告中的InvoiceStatus值(开放,付费,部分)进行搜索。我尝试了一些东西,但我无法得到任何工作。知道怎么做吗?

ALTER PROCEDURE [dbo].[Extranet_ClientMatterInvoices]
@BeginDate VARCHAR(max) = NULL,
@EndDate VARCHAR(max) = NULL,
@InvoiceStatus VARCHAR(MAX) = NULL

AS
SELECT m.ClientGroupID,
m.ClientID,
m.ClientName,
m.MatterCode,
m.[Area Of Law],
i.InvoiceNo,
i.InvoiceTotalAmount,
i.InvoiceFees,
i.InvoiceCosts,
m.mattername,
i.invoiceDate,
 CASE 
  WHEN i.InvoiceTotalAmount <= 0 THEN 'Paid'
  WHEN i.Total_PaidWithWO = 0 THEN 'Open'
  WHEN i.Total_PaidWithWO < i.InvoiceTotalAmount THEN 'Partial'
  WHEN i.Total_PaidWithWO >= i.InvoiceTotalAmount THEN 'Paid'
ELSE 'Open'
END AS 'InvoiceStatus'
 FROM [local].[lp2warehouse].dbo.lp2_matters m
 INNER JOIN [local].[lp2warehouse].dbo.lp2_invoices i 
ON m.mattercode = i.mattercode
WHERE (i.invoicedate BETWEEN ISNULL(@BeginDate,'01/01/1900') 
AND ISNULL(@EndDate,'12/31/9999'))
ORDER BY m.ClientGroupID,m.ClientID

1 个答案:

答案 0 :(得分:3)

将现有SELECT包装到派生表或CTE中,然后您可以在外部查询的InvoiceStatus过滤器中使用投影别名WHERE,即

SELECT * FROM
(
  SELECT 
   m.ClientGroupID,
   m.ClientID,
   ... other fields
   CASE 
     WHEN i.InvoiceTotalAmount <= 0 THEN 'Paid'
     WHEN i.Total_PaidWithWO = 0 THEN 'Open'
     WHEN i.Total_PaidWithWO < i.InvoiceTotalAmount THEN 'Partial'
     WHEN i.Total_PaidWithWO >= i.InvoiceTotalAmount THEN 'Paid'
     ELSE 'Open'
   END AS InvoiceStatus
 FROM ... same
 WHERE ... same
) derived
WHERE derived.InvoiceStatus = 'Partial';