如何在sql server表中安排数据

时间:2015-05-15 12:57:20

标签: sql-server sql-server-2008 tsql sql-server-2008-r2

我尝试了很多查询来达到预期的效果,我无法找到任何解决方案。

实际: -

ID | EmpDailyFee | EmpMonthlyFee | CompDailyFee | CompMnthlyFee

1        NULL         12            NULL               NULL

1         50         NULL           NULL               NULL

1         60         NULL           NULL               NULL

2        50           NULL           NULL               NULL

3        NULL          30            NULL               NULL

预期: -

ID | EmpDailyFee | EmpMonthlyFee | CompDailyFee | CompMnthlyFee

1        50            12            NULL               NULL

1        60            12            NULL               NULL

2        50           NULL           NULL               NULL

3        NULL          30            NULL               NULL

4 个答案:

答案 0 :(得分:3)

由于行共享相同的ID值但具有不同的EmpDailyFee / EmpMonthlyFee值,因此对我来说这看起来像是一种气味。但在这种特殊情况下,您可以得到这样的预期输出:

SELECT t1.ID, t1.EmpDailyFee, t2.EmpMonthlyFee
FROM @Test t1
INNER JOIN @Test t2 ON t1.ID = t2.ID
WHERE t1.EmpDailyFee IS NOT NULL AND t2.EmpMonthlyFee IS NOT NULL
UNION ALL
SELECT t1.ID, t1.EmpDailyFee, t1.EmpMonthlyFee
FROM @Test t1
WHERE (t1.EmpDailyFee IS NOT NULL OR t1.EmpMonthlyFee IS NOT NULL) AND t1.ID NOT IN
(
    SELECT t3.ID
    FROM @Test t3
        INNER JOIN @Test t2 ON t3.ID = t2.ID
    WHERE t3.EmpDailyFee IS NOT NULL AND t2.EmpMonthlyFee IS NOT NULL
)

已在SQL Fiddle

上测试过

注意:我没有包含CompDailyFeeCompMnthlyFee的原因是因为实际和预期结果的值都是NULL。我试图根据OP提供的内容编写一个“尽可能简单”的查询。

答案 1 :(得分:1)

如果您尝试插入或更新数据,这可能是解决方案,根据您的需要进行自定义

IF EXISTS (SELECT 1 FROM Employee WHERE ID = 1)
    UPDATE Employee SET EmpMonthlyFee= @Value WHERE ID = 1
ELSE
    INSERT Employee(ID,EmpDailyFee,EmpMonthlyFee,CompDailyFee,CompMnthlyFee)
    VALUES(1,NULL,@value,NULL,NULL)

答案 2 :(得分:1)

declare @t table (ID int,Empfee int,monthlyfee int,compdailyfee int,Cmpnymonthlyfee int)

insert into @t (ID,Empfee,monthlyfee,compdailyfee,Cmpnymonthlyfee)
values (1,NULL,12,NULL,NULL),
(1,50,NULL,NULL,NULL),
(1,60,NULL,NULL,NULL)
;with cte as (
select t.ID,t.Empfee,
tt.monthlyfee,
t.compdailyfee,
t.Cmpnymonthlyfee,
ROW_NUMBER()OVER(PARTITION BY t.ID,tt.monthlyfee ORDER BY t.ID,tt.monthlyfee)RN 
    from @t t  
    CROSS  APPLY @t tt
where t.Empfee IS  NULL OR tt.monthlyfee IS NOT NULL) 

select C.ID,
C.Empfee,
C.monthlyfee,
C.compdailyfee,
C.Cmpnymonthlyfee from cte c
where c.Empfee IS NOT NULL AND c.monthlyfee IS NOT NULL 

答案 3 :(得分:1)

也可以使用COALESCE完成。

SELECT T1.ID, 
       T2.EmpDailyFee, 
       COALESCE(T1.EmpMonthlyFee , T2.EmpMonthlyFee) EmpMonthlyFee, 
       COALESCE(T1.CompDailyFee , T2.CompDailyFee) CompDailyFee , 
       COALESCE(T1.CompMnthlyFee , T2.CompMnthlyFee) CompMnthlyFee 

FROM 

(SELECT * FROM Tab WHERE EmpDailyFee IS NULL)T1
JOIN
(SELECT * FROM Tab WHERE EmpDailyFee IS NOT NULL)T2
ON T1.ID = T2.ID

我已经走了一步,并假设第一行的值如果不为空则优先(对于OP中的第3列)。如果不需要,这部分可以忽略不计。