我可以 Return 在 SQL 服务器中将 Following Statement As Static 吗?

Can I Return Following Statement As Static in SQL Server?

  ------------------------------
  |  User Name   |   Falg       |
  -------------------------------
  |  Kapil       |  Attendance  |
  -------------------------------
  |  Kapil       |  Field       |
  --------------------------------
  |  Khan        |  Attendance  |
  -------------------------------
  |  Sri         |  Attendance  |
  -------------------------------
  |  Raja        |  Field       |
  -------------------------------

期望输出:

  --------------------------------------------
  |  User Name   |   Activity1  |  Activity2  |
  ---------------------------------------------
  |  Kapil       |  Attendance  |  Field      |
  ---------------------------------------------
  |  Khan        |  Attendance  |  Field      |
  ---------------------------------------------
  |  Sri         |  Attendance  | Null        |
  ---------------------------------------------- 

到目前为止我已经试过了 同样的查询是这样的

   Select User_Code, DCR_Actual_Date, Flag "Activity1" From Tbl_Sfa_DCR_Master 
Where DCR_Status in(1,2) and Flag ='A' 
and DCR_Actual_Date Between '2014-01-01' and '2014-12-31')T1 
On (T1.User_Code =T0.User_Code and T1.DCR_Actual_Date=T0.[DCR_Date]) 
Left Outer Join (Select User_Code, DCR_Actual_Date, Flag "Activity2" 
From Tbl_Sfa_DCR_Master Where DCR_Status in(1,2) 
and Flag ='F' and DCR_Actual_Date Between '2014-01-01' and '2014-12-31')T2 
On (T2.User_Code =T0.User_Code and T2.DCR_Actual_Date=T0.[DCR_Date])

谁能帮帮我。我可以将查询写成静态的吗?

试试这个。 Conditional Aggregate

SELECT [user name],
       Max(CASE
             WHEN Falg = 'Attendance' THEN Falg
           END) 'Activity1',
       Max(CASE
             WHEN Falg = 'Field' THEN 'Field'
           END) 'Activity2'
FROM   yourtable
GROUP  BY [User Name]

或使用pivot

SELECT *
FROM  (SELECT CASE Falg
                WHEN 'Attendance' THEN 'Activity1'
                WHEN 'Field' THEN 'Activity2'
              END act,
              *
       FROM  yourtable) A
      PIVOT (Max(Falg)
            FOR act IN ([Activity1],
                        [Activity2]))piv