Group By Sql Query。我怎么能创造?

时间:2018-03-13 15:07:15

标签: sql

我有这个问题:

@Echo Off
:AskDir
Set "dir_with_files="
Set /P "dir_with_files=location: "
If "%dir_with_files%"=="" GoTo AskDir
If "%dir_with_files:~-1%"=="\" Set "dir_with_files=%dir_with_files:~,-1%"
If Not Exist "%dir_with_files%\" GoTo :AskDir
Set "_rand=%dir_with_files%\%random%.organizer.lock.txt"
Type Nul>"%_rand%" 2>Nul && (Del "%_rand%") || GoTo :AskDir
If "%dir_with_files:~-1%"==":" Set "dir_with_files=%dir_with_files%\"
CD /D "%dir_with_files%" 2>Nul || Exit /B
For /D %%A In (*) Do If /I Not "%%~xA"=="" Move /-Y "%%A\*%%~xA">Nul 2>&1
Exit /B.

当我执行它时,我有这个列表

select AlarmGroup,AgentName from v_Dashboard_Alarms;

如果AlarmGroup!= Null,我想编写一个Group By AgentName查询 我想拿这份清单

AlarmGroup     AgentName
==========     ==========
GroupName        Thassos
GroupName        Thassos
GroupName        Thassos
NULL             Pythion
NULL             Metaxas
NULL             Metaxas
GroupName        Pilio
GroupName        Pilio

我该如何解决? 谢谢!

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

Select Distinct AlarmGroup, AgentName
from table
where AlarmGroup is null 
UNION ALL 
Select AlarmGroup, AgentName
from table
where AlarmGroup,AgentName is not null
group by AlarmGroup 

答案 1 :(得分:1)

在ANSI SQL中,您可以执行以下操作:

with t as (
      select t.*, row_number() over (order by alarmgroup) as seqnum
      from v_Dashboard_Alarms  t
     )
select alarmgroup, agentname
from t
group by (case when alarmgroup is null then seqnum end),
         alarmgroup, agentname;

row_number()的目的是为每一行分配不同的值。如果您已拥有唯一ID,请改用它。 group by然后根据看似明显的逻辑突破扩展组。

您也可以使用union all

执行此操作
select alarmgroup, agentname
from v_Dashboard_Alarms t
where alarmgroup is null
union all
select distinct alarmgroup, agentname
from v_Dashboard_Alarms t
where alarmgroup is not null;

第一个查询的优点是它只评估一次视图。