根据其他两个表值插入表中; SQL服务器

时间:2015-03-30 08:03:38

标签: sql sql-server tsql

enter image description here

有人可以指导我如何在不使用包含条件的情况下继续获取所需的输出

enter image description here

我尝试使用Unpivot,Case语句和Contains condition.But无法达到所需的输出。

2 个答案:

答案 0 :(得分:2)

您可以使用CASE

获得所需的结果
SELECT
    t1.Number,
    [First] =   
        CASE 
            WHEN t1.AAA >= 5 THEN 'Yes'
            WHEN t1.AAB >= 5 THEN 'Yes'
            WHEN t1.AAC >= 5 THEN 'Yes'
            WHEN t1.AAD >= 5 THEN 'Yes'
            ELSE 'No'
        END,
    [Second] = 
        CASE 
            WHEN t2.MMP >= 15 THEN 'Yes'
            WHEN t2.MMQ >= 15 THEN 'Yes'
            WHEN t2.MMA >= 15 THEN 'Yes'
            WHEN t2.MMC >= 15 THEN 'Yes'
            ELSE 'No'
        END
FROM BaseTable1 t1
INNER JOIN BaseTable2 t2
    ON t2.Number = t1.Number

你的设计并不好。我建议您对数据进行规范化,使其成为BaseTable(Number, Col, Value)

答案 1 :(得分:0)

尝试使用CASE表达式:

DECLARE @t1 TABLE(N INT, AAA MONEY, AAB MONEY, AAC MONEY, AAD MONEY)
DECLARE @t2 TABLE(N INT, MMP MONEY, MMQ MONEY, MMA MONEY, MMC MONEY)

INSERT INTO @t1 VALUES
(561, 5, 5.5, 6, 6.5),
(562, 3.5, 4, 3.6, 3)

INSERT INTO @t2 VALUES
(561, 10, 10, 13, 15),
(562, 12, 10, 9, 14)

SELECT t1.N, 
       CASE WHEN t1.AAA >= 5 OR t1.AAB >= 5 OR t1.AAC >= 5 OR t1.AAD >= 5 
            THEN 'Y' ELSE 'N' END AS First,
       CASE WHEN t2.MMP >= 15 OR t2.MMQ >= 15 OR t2.MMA >= 15 OR t2.MMC >= 15 
            THEN 'Y' ELSE 'N' END AS Second
FROM @t1 t1
JOIN @t2 t2 ON t1.N = t2.N

输出:

N   First   Second
561 Y       Y
562 N       N