根据特定条件从DB表中获取数据

时间:2015-10-02 17:00:10

标签: sql sql-server

我有2张表A和表B

表A

([Col A1], [Col A2], [Col A3])

表B

([Col B1], [Col B2], [Col B3])

现在我有一个查询来根据某些条件从表中获取数据

示例:

Select a.*,b.[Col B1]
from [Table A] a, [Table B] b
where a.[Col A1]= '0000'
and a.[Col A1] = b.[Col B1]

假设此查询返回5条记录。

Record 1 - Col A1 | Col A2 | Col A3 | Col B1
Record 2 - Col A1 | Col A2 | Col A3 | Col B1
Record 3 - Col A1 | Col A2 | Col A3 | Col B1
Record 4 - Col A1 | Col A2 | Col A3 | Col B1
Record 5 - Col A1 | Col A2 | Col A3 | Col B1

我要求添加以下条件

如果表B Col B3具有值(NOT NULL),那么除了原始结果外,还要添加如下所示的新记录

Record 1 - Col A1 | Col A2 | Col A3 | Col B1
Record 2 - Col A1 | Col A2 | Col A3 | Col B1
Record 3 - Col A1 | Col A2 | Col A3 | Col B1
Record 4 - Col A1 | Col A2 | Col A3 | Col B1
Record 5 - Col A1 | Col A2 | Col A3 | Col B1
**Record 6 - Col A1 | *Col B3* | Col A3 | Col B1**

任何建议

3 个答案:

答案 0 :(得分:1)

我认为您希望将一行基本上分成两行。所以你可能想要一个联盟:

select a.ColA1, a.ColA2, a.ColA3, b.ColB1
from TableA a inner join TableB b on b.ColB1 = a.ColA1
where a.ColA1 = '0000'
union all /* presumably you have no duplicates or want to keep them */
select a.ColA1, b.ColB3, a.ColA3, b.ColB1
from TableA a inner join TableB b on b.ColB1 = a.ColA1
where b.ColB3 is not null

单一查询肯定存在问题,但实际上并不值得麻烦:

select
    a.ColA1,
    case when n = 1 then a.ColA2 when n = 2 then b.ColB3 end as ColA2,
    a.ColA3,
    b.ColB1
from
    TableA a inner join TableB on b.ColB1 = a.ColA1,
    (select 1 n union all select 2) as splitter
where
    case
        when n = 1 and a.ColA1 = '0000' then 1
        when n = 2 and b.ColB3 is null then 1
    end = 1

您也可以查看unpivot,但我认为这也可能有点过分。

答案 1 :(得分:1)

我认为你最好的选择是联盟:

Select a.*,b.Col B1
from Table A a, Table B b
where a.Col A1= '0000'
and a.Col A1 = b.Col B1

UNION ALL

Select a.A1, a.B3, a.A3, b.B1
FROM TableA a 
    INNER JOIN TableB b ON a.A1 = b.B1
WHERE <your condition when you want this record>

UNION ALL执行的操作是执行第二个查询,并将第二个查询的结果集附加到第一个查询的结果集中。它堆叠结果集。 如果您的条件是,当存在将b.B3作为非Null值的记录时,您想要将记录添加到原始结果集,那么您在第二个查询上的WHERE语句是UNION&#39; d in将是:

WHERE b.B3 IS NOT NULL

答案 2 :(得分:0)

似乎UNION会起作用。像这样:

SELECT A.A1, A.A2, A.A3, B.B1
FROM A
    INNER JOIN B 
        ON A.A1 = B.B1
WHERE A1 = '0000'

UNION

SELECT A.A1, B.B3, A.A3, B.B1
FROM A
    INNER JOIN B 
        ON A.A1 = B.B1
WHERE A.A1 = '0000' AND B.B3 IS NOT NULL