TSQL包含有条件的帐户

时间:2018-07-11 17:06:40

标签: sql-server tsql case where

我有一个表格,目前包括所有这样的帐户:

enter image description here

我需要过滤,如果公司= MMCR和HSSA AND天数> = 90,那么我需要该报告以包括公司。不论发送天数,都包括所有其他公司。

这就是我要寻找的:

enter image description here

4 个答案:

答案 0 :(得分:1)

您可以使用简单的OR来完成此操作:

SELECT Account, Invoice, Company, DaysSent
    FROM YourTable
    WHERE Company NOT IN('MMCR', 'HSSA')
       OR (Company IN('MMCR', 'HSSA') AND DaysSent >= 90);

答案 1 :(得分:1)

或更简单的答案:

SELECT [Account], [Invoice #], [Company], [Days Sent]
FROM [dbo].[YourTable]
WHERE NOT ([Company] IN ('MMCR', 'HSSA') AND [Days Sent] < 90);

答案 2 :(得分:0)

这应该做到:

SELECT ACCOUNT, INVOICE, COMPANY, DAYS_SENT FROM TABLE1
WHERE (COMPANY = 'MMCR' AND DAYS_SENT >= 90) OR (COMPANY = 'HSSA' AND DAYS_SENT >= 90)

UNION

SELECT ACCOUNT, INVOICE, COMPANY, DAYS_SENT FROM TABLE1
ACCOUNT NOT IN (
SELECT ACCOUNT
WHERE (COMPANY = 'MMCR' AND DAYS_SENT >= 90) OR (COMPANY = 'HSSA' AND DAYS_SENT >= 90)
)
  • 联合顶部查询与底部查询。
  • 排名靠前的查询将包含2家公司及其日期范围
  • 底部查询是顶部查询中没有的所有内容。

有很多方法可以解决此问题,我只是喜欢这种方法,因为我觉得它易于阅读和理解(尤其是以后要更新时!)

答案 3 :(得分:0)

   You can do like this  

     SELECT ACCOUNT, INVOICE, COMPANY, DAYS_SENT FROM TABLE1
        WHERE Company   in ('MMCR', 'HSSA') AND DAYS_SENT >= 90 

        UNION

        SELECT ACCOUNT, INVOICE, COMPANY, DAYS_SENT FROM TABLE1 Where 
        ACCOUNT NOT IN  ('MMCR', 'HSSA')