SQL Server多次连接到同一个表,其中on子句具有和

时间:2016-09-22 19:54:53

标签: sql sql-server inner-join

我正在尝试获取多行数据并将它们合并为一行。输入数据如下所示:

prop_name          tocid    str_val
Year              181030    10
Billing Cycle     181030    2
Month             181030    08

我希望输出为:

10    2    08

我正在尝试这段代码:

select 
pv1.str_val
,pv2.str_val
,p3.str
from propdef pd
    inner join propval pv1 on pd.prop_id = pv1.prop_id and pd.prop_name = 'Year'
    inner join propval pv2 on pd.prop_id = pv2.prop_id and pd.prop_name = 'Billing Cycle'
    inner join propval pv3 on pd.prop_id = pv3.prop_id and pd.prop_name = 'Month'
where 
    pv1.tocid in (181030)

这不会返回任何数据。我以为我应该能够在同一张桌子上进行内连接。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

无需加入:

SELECT  tocid,
        MIN(CASE WHEN prop_name = 'Year' THEN str_val END) [Year],
        MIN(CASE WHEN prop_name = 'Billing Cycle' THEN str_val END) [Billing Cycle],
        MIN(CASE WHEN prop_name = 'Month' THEN str_val END) [Month]
FROM YourTable
GROUP BY tocid;