通过Union Select ALL添加订单

时间:2017-09-20 20:45:20

标签: sql

我使用以下查询创建ssrs参数,需要按姓氏排序

SELECT  Lastname + ', ' + FirstName + ' ' + '(' + INPN + ')' as Agent

FROM tblagents where agentcode in (SELECT AgentCode from AgentDetail)

UNION
SELECT ' ALL'  AS Agent 

我首先尝试在工会之前使用订单。

然后我尝试将这一切包装在select * from

SELECT  *
from (
    (SELECT Lastname, Firstname, INPN FROM tblAgents where agentcode in (SELECT AgentCode from AgentDetail) )
    UNION SELECT ' ALL' AS Agent
) 

也没用。 我如何在查询中按姓氏订购?

2 个答案:

答案 0 :(得分:3)

最后是sintaxis order by。不在工会之前

SELECT * FROM Table1
UNION 
SELECT * FROM Table2
ORDER BY <somefield>

在你的情况下是这样的:

SELECT Lastname as OrderField, 
       Lastname + ', ' + FirstName + ' ' + '(' + INPN + ')' as Agent

FROM tblagents 
WHERE agentcode in (SELECT AgentCode FROM AgentDetail)

UNION ALL 

SELECT 'AAAAA' as OrderField,
        'ALL'  AS Agent 
ORDER BY OrderField

答案 1 :(得分:1)

SELECT T.Lastname, T.Firstname, T.INPN , T.Agent 
FROM (
        SELECT Lastname, Firstname, INPN , null as Agent
        FROM tblAgents 
        WEHRE agentcode in (SELECT AgentCode 
                            from AgentDetail)
        UNION 
        SELECT null,null,null, 'ALL' AS Agent
      ) AS T
ORDER BY T.Lastname asc