sql-server - SQL Server : query to get multiple results in one field

标签 sql-server sql-server-2008 t-sql syntax join

我有 2 个 SQL Server 表

装备信息

equip_id | asset_no
-------------------
1        | CAL-1 
2        | MIC-1
...

equip_insp

insp_id | equip_id | insp_name   | due_date
----------------------------------------------
1       | 1        | Calibration | 2014-01-10
2       | 1        | Maintenance | 2014-01-10
3       | 1        | Check       | 2014-02-10
4       | 2        | Calibration | 2014-11-04
5       | 2        | Maintenance | 2014-05-04
...

equip_id 没有 2 个相似的 insp_name,但这不太重要。

一句话,我想帮助我使用 T-SQL 语法来获取不同设备的列表,以及“下一次”检查或检查(如果 due_date 相同)和 due_date。

可能会出现这样的情况:对于同一 due_date,有多次检查,因此在这种情况下,必须将其连接并显示在一个字段中(例如:“校准、维护”)

此查询的结果应类似于:

equip_id | asset_no | inspection               | due_date
-----------------------------------------------------------
1        | CAL-1    | Calibration, Maintenance | 2014-01-10
2        | MIC-1    | Maintenance              | 2014-05-04

最佳答案

使用 @Shiva 的 SqlFiddle :

create table equip_info (
  equip_id int not null,
   asset_no nvarchar(10) not null
  );

insert into equip_info (equip_id, asset_no) values
(1, 'CAL-1'),
(2, 'MIC-1');

create table equip_insp (
  insp_id  int not null,
  equip_id  int not null,
  insp_name nvarchar(50) not null,
  due_date datetime not null
  );

insert into equip_insp values
(1,1,'Calibration','10/01/2014'),
(2,1,'Maintenance','10/01/2014'),
(3,1,'Check','10/02/2014'),
(4,2,'Calibration','04/11/2014'),
(5,2,'Maintenance','04/05/2014');

这就是您所需要的:

;WITH DataSource AS
(
  select inf.equip_id
        ,asset_no
        ,MIN(due_date) as [due_date]
  from equip_info inf
  inner join equip_insp ins
    on inf.[equip_id] = ins.[equip_id]
  GROUP BY inf.equip_id
          ,asset_no
)
SELECT equip_id
      ,asset_no
      ,SUBSTRING((SELECT DISTINCT ', ' + insp_name 
        FROM equip_insp 
        WHERE due_date = DS.due_date
          AND equip_id = DS.equip_id
        FOR XML PATH('')
       ),2,4000) as inspection
      ,due_date
FROM DataSource DS

这是输出:

enter image description here

Here是完整的工作示例。

关于sql-server - SQL Server : query to get multiple results in one field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20776703/

相关文章:

azure - 在 SSMS 中使用 T-SQL 删除 Azure SQL 数据库

java - 使用 JDBC 语句执行查询时出现 NullPointerException

sql - SQL Server 中第一个实例 0 rest other 变成 1

SQL Server 存储过程更新并返回单个值

sql - Insert 语句中的多个 Select 语句出错

sql-server - 从 SQL Azure 迁移到 SQL Server

sql - 从表贷方借方列中选择运行余额

sql-server - Azure PaaS 逻辑服务器创建时间

sql server 更新查询失败

sql - 在雪花中实现sql "JOIN"返回策略的最佳实践