相同列,相同表 - 查询

时间:2014-10-08 07:02:24

标签: sql sql-server

SELECT
    [SSI$Sales Price].[Sales Code] AS CUSTOMER
    ,[SSI$Sales Price].[Sales Code] AS SRP
    ,[SSI$Sales Price].[Item No_] AS [Item No]
    ,[SSI$Sales Price].[Variant Code]
    ,[SSI$Sales Price].[Unit of Measure Code] AS [Unit of Measure]
    ,[SSI$Sales Price].[Unit Price] AS SALES1
    ,[SSI$Sales Price].[Unit Price] AS SALES2
    ,SSI$Item.[Unit Cost]
    ,[SSI$Sales Price].[Starting Date]
    ,[SSI$Sales Price].[Ending Date]


FROM [SSI$Sales Price]

LEFT JOIN SSI$Item
    ON [SSI$Sales Price].[Item No_] = SSI$Item.No_

JOIN [SSI$Sales Price] AS CUSTOMER
    ON [SSI$Sales Price].[Item No_] = [SSI$Sales Price].[Item No_] AND [SSI$Sales Price].[Variant Code] = [SSI$Sales Price].[Variant Code] 

JOIN [SSI$Sales Price] AS SRP
    ON [SSI$Sales Price].[Item No_] = [SSI$Sales Price].[Item No_] AND [SSI$Sales Price].[Variant Code] = [SSI$Sales Price].[Variant Code] 

WHERE
    [SSI$Sales Price].[Sales Code] = 'C00020' AND
    [SSI$Sales Price].[Sales Code] = 'SRP' AND
    [SSI$Sales Price].[Sales Type] = '0'

在运行上述内容时,我没有任何结果。

Bellow是一个样本数据和预期结果。

表1

Col1   Col2   Col3
 A     Item1   100
 A     Item2   200
 A     Item3   300
 B     Item1   400
 B     Item2   500
 B     Item3   600

SQL查询结果

  Col1    Col2    Col3    Col4    Col5
 Item1     A      100      B       400
 Item2     A      200      B       500 
 Item3     A      300      B       600

1 个答案:

答案 0 :(得分:0)

select distinct a.col2 as col1,a.col1 as col2,a.col3 as col3,b.col1 as col4,b.col3 as col5
(select col1,col2,col3 from table where col1='A')a
join
(select col1,col2,col3 from table where col1='B')b
on a.col1=b.col1

这是示例,使用必需的过滤器制定内部查询。