在SELECT中将两个列表联合在一起

时间:2016-04-30 03:05:48

标签: sql sql-server database sql-server-2014

我有两张桌子:

第一张表:

Team_Code           ID
----------------------------------
433                 203994834
436                 203994834 
436                 309228372
435                 309228373
434                 309228374
433                 399064113

第二张表:

number_of_times       Team_Code
------------------------------------
3                     433
2                     434
1                     435
1                     436

我想将这两个表合并成一个看起来像的表:

number_of_times    Team_Code      ID
---------------------------------------------
3                  433            203994834
2                  434            309228374  
1                  435            309228373
1                  436            203994834

......等 - (Id可以出现多次)

2 个答案:

答案 0 :(得分:2)

; with 
query1 as
(
-- Your Query 1
SELECT * FROM Fireman_Team WHERE Team_Code in (
  SELECT Answer.Team_Code FROM Answer WHERE
  Answer.Call_Number IN(
    SELECT Call_Number FROM (SELECT * FROM Call WHERE Call.Time_Started
      BETWEEN ('2016-01-01 00:00:00') AND 
      ('2016-01-31 23:59:59')) AS SSS)) 
),
query2 as
(
-- Your Query 2
SELECT COUNT(Team_Code) as number_of_times, 
Team_Code FROM (SELECT Answer.Team_Code FROM Answer WHERE
  Answer.Call_Number IN(
    SELECT Call_Number FROM (SELECT * FROM Call WHERE Call.Time_Started
      BETWEEN ('2016-01-01 00:00:00') AND 
      ('2016-01-31 23:59:59')) AS SSS)
) AS re GROUP BY Team_Code
)
select *
from   query1 q1 inner join query2 q2 on q1.Team_Code = q2.Team_Code

答案 1 :(得分:1)

使用CTE提高可读性 -

function selectGender($gender,$out=false)
    {
        // You may not need these 3 lines if $gender is either empty, M, or F //
        $filter = array('M','F');
        if(!in_array($gender,$filter))
            $gender = false;

        if($gender == $out)
            return ' selected="selected"'; 
    }

while($row = mysqli_fetch_assoc($result)){ 
    $gender =  $row['gender'];
    $output.= "Gender: <select name='gender'>   
<option value='0'".selectGender($gender).">Select gender</option> 
<option value='M'".selectGender($gender,'M').">Male</option>  
<option value='F'".selectGender($gender,'F').">Female</option></select>";
}