經過大量搜索web和Stackoverflow後,仍在尋找一種方法來使用ALIAS來返回列而不產生新的行/行。sql,case when then
以下工作創建列「Sig_1_Emp」和「Sig_3_Staff」,但Sig_1_Emp和Sig_3_Staff的數據不在同一行,而是兩行。
CASE
WHEN VisitSignatures.order = 1 THEN Employees.last_name
END AS Sig_1_Emp,
CASE
WHEN VisitSignatures.order = 3 THEN Employees.last_name
END AS Sig_3_Staff
因此,會像下面的工作?
CASE WHEN VisitSignatures.order = 1 THEN Employees.last_name AS Sig_1_Emp
WHEN VisitSignatures.order = 3 THEN Employees.last_name AS Sig_3_Staff
END
下面是完整的查詢:
Select
CV.clientvisit_id,
CV.program_id,
CV.visittype,
CV.non_billable,
CV.rev_timein,
CASE
WHEN CVSig.ord = 1 THEN Employees.last_name
ELSE Null
END AS Sig_1_Emp,
CASE
WHEN CVSig.ord = 3 THEN Employees.last_name
ELSE Null
END AS Sig_3_Staff
From CV
Inner Join CVSig On CV.clientvisit_id = CVSig.clientvisit_id
Inner Join EmpSig On CVSig.employeesignature_id = EmpSig.employeesignature_id
Inner Join Employees On EmpSig.emp_id = Employees.emp_id
Where
CV.program_id In (121, 123)
And CV.rev_timein >= @param1
And CV.rev_timein <= DATEADD(d, 1, @param2)
和結果的一個樣本:
+----------------+------------+-----------+------------+-----------+-------------+
| clientvisit_id | program_id | visittype | rev_timein | sig_1_emp | sig_3_staff |
+----------------+------------+-----------+------------+-----------+-------------+
| 1001 | 121 | M_Mgmnt | 7/1/2014 | | Nurse_Pat |
| 1001 | 121 | M_Mgmnt | 7/1/2014 | Doc_Sue | |
+----------------+------------+-----------+------------+-----------+-------------+
而這正是我希望acheive:
+----------------+------------+-----------+------------+-----------+-------------+
| clientvisit_id | program_id | visittype | rev_timein | sig_1_emp | sig_3_staff |
+----------------+------------+-----------+------------+-----------+-------------+
| 1001 | 121 | M_Mgmnt | 7/1/2014 | Doc_Sue | Nurse_Pat |
+----------------+------------+-----------+------------+-----------+-------------+
我對此感到抱歉,謝謝你耐心等待。 如果這不能說明我的問題,請刪除這篇文章。
你不能給一個字段多個別名,所以底部'CASE'不起作用。一些示例數據和所需的輸出將會很有幫助,同樣,您使用的是哪個數據庫? – 2014-10-03 19:21:20
嘗試運行它,看看會發生什麼。 (破壞者:它不會工作) – Siyual 2014-10-03 19:21:43
你似乎在尋找數據透視技術,但是你錯過了一個重要的部分,聚合函數(通常是'MAX'):你的第一個代碼片段應該是'SELECT MAX(CASE ... END) AS Sig_1_Emp,MAX(CASE ... END)AS Sig_3_staff,.... GROUP BY ...' – a1ex07 2014-10-03 19:27:01