我有一个名单,其中包含一个支票帐户和/或一个与其直接存款相关联的储蓄帐户。 22表示检查,32表示节省。
如果他们在列中只有一个支票帐户(22)或只有一个储蓄帐户(32),那么我希望在其旁边的列中有一个'100%'。但是,如果一个人有支票和储蓄账户,我想留空。 (我们必须手动查看其他软件以获取信息)
实施例
Employee # Account Allocated %
100 22
100 32
101 22 100
102 32 100
我该怎么做?
答案 0 :(得分:1)
我使用这样的东西:
UPDATE t1
SET [Allocated %] = 100
FROM YourTable t1
WHERE t1.Account IN (22,32)
AND NOT EXISTS (
SELECT 1
FROM YourTable t2
WHERE t2.[Employee #] = t1.[Employee #]
AND t2.Account IN (22,32)
AND t2.Account <> t1.Account
)
但是,当然,您应该首先检查它是否正确:
SELECT *
FROM YourTable
WHERE YourTable.Account IN (22,32)
AND YourTable.[Employee #] IN (
SELECT t1.[Employee #]
FROM YourTable t1
WHERE t1.Account IN (22,32)
AND NOT EXISTS (
SELECT 1
FROM YourTable t2
WHERE t2.[Employee #] = t1.[Employee #]
AND t2.Account <> t1.Account
AND t2.Account IN (22,32)
)
)
ORDER BY [Employee #], Account;
答案 1 :(得分:0)
您可以按员工#进行分组,并使用一个标志来检查22和一个使用case语句检查32的标志。
测试场景
select *
into ##tempAccounts
from (
select EmployeeNum = 100, Account = 22
union all select EmployeeNum = 100, Account = 32
union all select EmployeeNum = 101, Account = 22
union all select EmployeeNum = 102, Account = 32
) x
select * from ##tempAccounts
select
Accounts.EmployeeNum,
Accounts.Account,
case when AccountStatHelper.Has22 = 1 and AccountStatHelper.Has32 = 1 then Null else '100%' end
from ##tempAccounts as Accounts
left join
(
select
EmployeeNum,
Has22 = max(case when Account = 22 then 1 else 0 end),
Has32 = max(case when Account = 32 then 1 else 0 end)
from ##tempAccounts
group by EmployeeNum
) AccountStatHelper on Accounts.EmployeeNum = AccountStatHelper.EmployeeNum
drop table ##tempAccounts
<强>结果强>
EmployeeNum Account
----------- ----------- ----
100 22 NULL
100 32 NULL
101 22 100%
102 32 100%
答案 2 :(得分:0)
一个真正简单的方法就是这样:
SELECT *, CASE WHEN
(SELECT COUNT(*) FROM Accounts WHERE EmpNo = A.EmpNo) = 1
THEN 100 ELSE NULL END AS Allocation FROM Accounts A
这不会检查22
或32
状态。它只是看他们是否有多种类型的帐户。这可能是最简单的方法,假设您的逻辑是他们有多个帐户,那么它需要为100。