如何在SQL Server中使用like和not like相同的字段

时间:2015-06-22 07:07:19

标签: sql sql-server

TBL_Transaction类型:

Credit
Debit

TBL_Account类型:

1 Saving Account
2 Loan Account 
3 NRI Account

TBL_Transaction:

Sr. Name         AccType   TransType  DateOfTransaction  Amount
1   mano         saving    credit     2014/12/01           5000   
2   john         Loan      Debit      2014/12/02          10000

我想记录哪个帐户持有人信用流程,他应该在特定日期记帐。

结果: 名称AccountType

我尝试此查询,但无法正常工作

SELECT 
    NAME,
    ACCOUNTTYPENAME,
    ........... 
GROUP BY 
    NAME,
    ACCOUNTTYPENAME
WHERE
    TRANSACTIONTYPENAME LIKE 'CREDIT%' AND NOT LIKE 'DEBIT%'

5 个答案:

答案 0 :(得分:0)

试试这个

SELECT NAME,ACCOUNTTYPENAME,........... 
WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' AND TRANSACTIONTYPENAME NOT LIKE 
'DEBIT%'
GROUP BY NAME,ACCOUNTTYPENAME

答案 1 :(得分:0)

我知道你需要找到只有信用交易的名字。您可以执行子查询

SELECT NAME,ACCOUNTTYPENAME from tbl_Transaction
WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' AND 
Name not in
(SELECT NAME from tbl_Transaction
WHERE TRANSACTIONTYPENAME LIKE 'DEBIT%')

或使用apply子句如下

SELECT NAME,ACCOUNTTYPENAME from TBL_Transaction transOuter
outer apply
(
    select count(*) as totalCredit from TBL_Transaction
    where TRANSACTIONTYPENAME LIKE 'CREDIT%'
    and NAME = transOuter.Name
) credit
outer apply
(
    select count(*) as totalDebit from TBL_Transaction
    where TRANSACTIONTYPENAME LIKE 'DEBIT%'
    and NAME = transOuter.Name
) debit
WHERE 
    credit.totalCredit > 0 
    and debit.totalDebit < 1

答案 2 :(得分:0)

尝试此查询

SELECT NAME,ACCOUNTTYPENAME
WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' OR
(TRANSACTIONTYPENAME LIKE 'CREDIT%' and (TRANSACTIONTYPENAME LIKE 'DEBIT%' and DateOfTransaction ='2014/12/01'))
 GROUP BY NAME,ACCOUNTTYPENAME

答案 3 :(得分:0)

这只是一个小的语法错误。

根据您给定的代码示例,将其更改为:

SELECT NAME,ACCOUNTTYPENAME,........... 
WHERE TRANSACTIONTYPENAME LIKE 'CREDIT%' 
      AND TRANSACTIONTYPENAME  NOT LIKE 'DEBIT%'
GROUP BY NAME,ACCOUNTTYPENAME

你的小组处于错误的位置。此外,您忘记再次提及TRANSACTIONTYPENAME第二个过滤器。

答案 4 :(得分:0)

最后我得到了一个答案,其中有计数(例如,当trnanstypename喜欢&#39; d%&#39;)=&#39; 0&#39; .Thanku试过