我在SQL Server 2012工作,我想要实现的是以下三种标准形式,这里我希望这是有道理的
使用类似于以下的数据,如果我有两个总价值的合同>每行的每个用户代码为0,那么结果我需要是多个合同'例如下面的网站52,70,309,如果我有两个合同,其中有一个总价值>仅在1行中为0,则结果将是总值为> 1的用户的合同名称。例如0网站520,最后如果我有一个合同只有一个,那么这只是导致给定的合同名称,例如网站600.
Site UserCode User Name Contract Name Total Val
----------------------------------------------------------------------
52 10000123 Miss Brenda Smith Perm Contract 425.00
52 10000123 Miss Brenda Smith Temp Contract 772.00
70 10000300 Mr Paul Jones Perm Contract 877.00
70 10000300 Mr Paul Jones Another Contract 29.00
309 10000297 Mrs Annette Curtain Yet Another Contract 255.00
309 10000297 Mrs Annette Curtain Perm Contract 61.00
520 10000140 Miss Alison Smith Perm Contract 425.00
520 10000140 Miss Alison Smith Temp Contract 0.00
600 10000200 Mr Steve Myself Perm Contract 100.00
这对我来说是一个严重的问题,而且我已经撞墙了,不能做到这一点,它让我发疯,如果有人可以帮助我,我会喜欢它。我已尝试过各种案例陈述等,但脑部崩溃了。它可能很简单,但已经盯着它看了很久我已经失明了。
答案 0 :(得分:0)
将其分解为逻辑段。我想不出一个可以处理你的条件的查询,所以我写了3个,我union
他们在一起。
它并不完美,但它确实有效。
declare @contracts table
(
Site INT,
UserCode INT,
UserName VARCHAR(100),
ContractName VARCHAR(100),
TotalVal MONEY
);
INSERT INTO @contracts (Site,UserCode,UserName,ContractName,TotalVal) VALUES
(52, 10000123, 'Miss Brenda Smith', 'Perm Contract', 425.00),
(52, 10000123, 'Miss Brenda Smith', 'Temp Contract', 772.00),
(70, 10000300, 'Mr Paul Jones', 'Perm Contract', 877.00),
(70, 10000300, 'Mr Paul Jones', 'Another Contract', 29.00),
(309,10000297, 'Mrs Annette Curtain', 'Yet Another Contract', 255.00),
(309,10000297, 'Mrs Annette Curtain', 'Perm Contract', 61.00),
(520,10000140, 'Miss Alison Smith', 'Perm Contract', 425.00),
(520,10000140, 'Miss Alison Smith', 'Temp Contract', 0.00),
(600,10000200, 'Mr Steve Myself', 'Perm Contract', 100.00);
select t1.Site, UserCode, UserName, 'multiple contracts', SUM(TotalVal) as totalvalue
from @contracts t1
join (select site from @contracts where TotalVal>0 group by Site having COUNT(*)>1) as morethan1greater0
on t1.Site=morethan1greater0.Site
group by t1.Site, UserCode, UserName
union all
select t1.Site, UserCode, UserName, ContractName, SUM(t1.TotalVal) as totalvalue
from @contracts t1
join (select site, sum(TotalVal) TotalVal from @contracts group by Site having COUNT(*)>1) as morethan1only1greater0
on t1.Site=morethan1only1greater0.Site
and t1.TotalVal=morethan1only1greater0.TotalVal
group by t1.Site, UserCode, UserName, ContractName
union all
select t1.Site, UserCode, UserName, ContractName, SUM(TotalVal) as totalvalue
from @contracts t1
join (select site from @contracts group by Site having COUNT(*)=1) as only1
on t1.Site=only1.Site
group by t1.Site, UserCode, UserName, ContractName