具有多个连接的SQL Server聚合

时间:2017-04-27 13:26:17

标签: sql sql-server join aggregation

我正在尝试从SQL Servre中的3个表中连接数据并在结果中显示:

  • 实体的别名
  • 如果实体是虚拟的
  • 最后一个日期(如果已知)
  • 值(如果已知)

我试过了:

select 
    sr.alias, c.virtual, max(d.date) date
from 
    App_references sr 
join 
    Sensor c on (c.id_capteur = sr.id_capteur) 
left join 
    Sensor_data d on (c.id_capteur = d.id_capteur)
group by 
    d.id_capteur, sr.alias, c.virtual
order by 
    sr.alias

这是数据库方案:

CREATE TABLE [dbo].[App_reference]
(
    [id_ref] [int] IDENTITY(1,1) NOT NULL,
    [alias] [varchar](60) NOT NULL,
    [id_capteur] [int] NOT NULL,
 CONSTRAINT [PK_App_reference] PRIMARY KEY CLUSTERED 
(
    [id_ref] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Sensor]
(
    [id_capteur] [int] IDENTITY(1,1) NOT NULL,
    [name] [varchar](50) NOT NULL,
    [virtual] [tinyint] NULL,
    [unite] [varchar](5) NULL,
    [id_type] [int] NOT NULL,
 CONSTRAINT [PK_Sensor] PRIMARY KEY CLUSTERED 
(
    [id_capteur] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[Sensor_data]
(
    [id_entry] [int] IDENTITY(1,1) NOT NULL,
    [id_capteur] [int] NOT NULL,
    [value] [xml] NOT NULL,
    [date] [datetime] NOT NULL,
 CONSTRAINT [PK_Sensor_data] PRIMARY KEY CLUSTERED 
(
    [id_entry] ASC,
    [id_capteur] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

假设每个列如“id_%”都通过外键链接。

请求顶部通过,我有价值:

alias               virtual date
Place 1 (Physique)  0       2017-04-27 14:58:42.423
Place 2             1       NULL
Place 3             1       NULL

但是我试图通过这样做来选择值:

select 
    sr.alias, c.virtual, max(d.date) date, d.value
from 
    Citopia_test.dbo.Smartparking_reference sr 
join 
    Citopia_test.dbo.Sensor c on (c.id_capteur = sr.id_capteur) 
left join 
    Citopia_test.dbo.Sensor_data d on (c.id_capteur = d.id_capteur)
group by 
    d.id_capteur, sr.alias, c.virtual
order by 
    sr.alias

我收到了这个错误:

  

列'Sensor_data.value'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

所以我尝试了一些事情,例如在组中添加列但没有任何更改。

1 个答案:

答案 0 :(得分:0)

您可能希望记录中的值具有最大日期。使用ROW_NUMBER获取这些记录。

select alias, virtual, date, value
from
(
  select 
    sr.alias, c.virtual, d.date, d.value,
    row_number() over (partition by sr.alias order by d.date desc) as rn
  from Citopia_test.dbo.Smartparking_reference sr 
  join Citopia_test.dbo.Sensor c on (c.id_capteur = sr.id_capteur) 
  left join Citopia_test.dbo.Sensor_data d on (c.id_capteur = d.id_capteur)
) numbered
where rn = 1
order by sr.alias;

每次sr.alias可以获得一行。如果您想要每sr.alias + c.virtual行一行,请相应更改partition by子句。