加入两个表,同时转动sql server 2008

时间:2014-05-09 11:47:37

标签: sql sql-server sql-server-2008 join

我有两张桌子

表1

SegmentNo  PassingPotencies
1           8
2           10

表2

BatchAvg     Total   TotalSegments  TotalPassed
106.22        20          2            18

我想通过简单登录加入两个表。如果表1中的Passingpotencies不等于10,那么该段失败,反之亦然。最终结果看起来应该是这样的

TableResult

BatchAvg     Total     TotalSegments     TotalPassed     Segment1     Segment2
106.22         20           2               18              Fail        Pass

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:1)

根据您当前的设计,这是您可以实现的(最接近的)。

在此处查看演示http://sqlfiddle.com/#!3/e86f5/5

select distinct BATCHAVG,
TOTAL,
TOTALSEGMENTS,
TOTALPASSED,
SegmentNo,
case when PASSINGPOTENCIES <> 10 then 'Failed'
else 'Passed' end as SegmentStatus
from
(
select * from table2,table1
 ) X

以上查询将导致

enter image description here

答案 1 :(得分:1)

这将适用于您的实际场景。在此处查看演示:SQLFiddle

首先,加入两个表:

SELECT 
    T2.BATCHAVG
,   T2.TOTAL
,   T2.TOTALSEGMENTS
,   T2.TOTALPASSED
,   T1.SEGMENTNO
,   (CASE WHEN T1.PASSINGPOTENCIES >= 10 THEN 'PASSED' ELSE 'FAILED' END)   AS SEGMENT
INTO TABLE3
FROM TABLE1 T1
CROSS JOIN TABLE2 T2

然后,像这样选择此表。它是某种PIVOT:

SELECT 
    T.BATCHAVG
,   T.TOTAL
,   T.TOTALSEGMENTS
,   T.TOTALPASSED
,   MAX(T.SEGMENT1)     AS SEGMENT1
,   MAX(T.SEGMENT2)     AS SEGMENT2
FROM (
SELECT 
    T1.BATCHAVG
,   T1.TOTAL
,   T1.TOTALSEGMENTS
,   T1.TOTALPASSED
,   (CASE WHEN T1.SEGMENTNO = '1' THEN T1.SEGMENT END) AS SEGMENT1
,   (CASE WHEN T1.SEGMENTNO = '2' THEN T1.SEGMENT END) AS SEGMENT2
FROM TABLE3 T1
) T
GROUP BY
    T.BATCHAVG
,   T.TOTAL
,   T.TOTALSEGMENTS
,   T.TOTALPASSED