在SQL Server中的不同列中选择一个列数据

时间:2017-08-08 14:07:45

标签: sql sql-server

我必须匹配两个表table1和table2,对于table1的一行我在表2中有两行或更多行,我想在一行中显示它们。

现在我有以下内容:

0

输出:

Select
    a.[ID], b.[Description]
From 
    table1 a, table2 b 
Where 
    a.[ID] = b.[ID];

我想得到以下结果

[ID] | [Description]
-----+--------------
1    | Fee
1    | Domestic Fee
2    | Fee
2    | International Fee 

提前谢谢你:)

4 个答案:

答案 0 :(得分:1)

如果您有多个描述,则可以使用Pivot,如下所示:

Select * from (
    Select *, RowN = Concat('Description', Row_Number() over (partition by Id order by Id)) from #description ) a
    pivot (max([Description]) for RowN in ([Description1],[Description2])) p

输出如下:

+----+--------------+-------------------+
| Id | Description1 |   Description2    |
+----+--------------+-------------------+
|  1 | Fee          | Domestic Fee      |
|  2 | Fee          | International Fee |
+----+--------------+-------------------+

答案 1 :(得分:1)

这是我的交叉应用运算符

的建议

数据prepartaion:

create table tst_1 (id int, dsc nvarchar(30))

insert into tst_1 (id, dsc)
values (1,'Fee'),(1,'Domestic Fee'),(2,'Fee'),(2,'International Fee')

接下来简单选择您要查找的jon show数据:

select t1.id, t1.dsc, x.dsc
from tst_1 t1
cross apply ( select row_number() over (order by id) as lp
                                        ,id
                                        ,dsc
                            from tst_1 )x
where x.id = t1.id and x.dsc <> t1.dsc
and lp%2 = 0

tst_1可以是基于您提问的select ...的视图。

答案 2 :(得分:0)

Select
    a.[ID],a.[Description], b.[Description]
From 
    table1 a left outer join table2 b 
on
    a.[ID] = b.[ID];``

答案 3 :(得分:0)

试试这个:

 public class Form1ViewModel
{
    public Form1ViewModel()
    {
        TestAction = () => Observable.Start(() => { MessageBox.Show("Initial step"); });
        TestCommand = ReactiveCommand.CreateFromObservable(()=>TestAction());
        TestCommand.ThrownExceptions.Subscribe(ex => MessageBox.Show(string.Format("Something went wrong while executing test command: {0}", ex)));
        TestAction = () => Observable.Start(() => { MessageBox.Show("Another step"); });

    }
    public ReactiveCommand TestCommand { get; set; }
    public Func<IObservable<Unit>> TestAction { get; set; }
}