首页 > 解决方案 > 如果有多个名称而不是多行 SQL Server,如何在一行中选择所有测试名称?

问题描述

我有以下 SQL Serverselect语句:

SELECT 
    a.patient_no AS 'File No', 
    b.order_id AS 'Order Id',  
    e.testname AS 'Test'
FROM 
    patients a, lab_orders b, customers c, order_details d, labtests e  
WHERE 
    a.patient_no = b.patient_no 
    AND b.custid = c.custid
    AND b.order_id = d.order_id 
    AND d.testid = e.testid
    AND c.CustId > 1
    AND CAST(b.order_date AS TIME) BETWEEN '01:00:00' AND '23:50:50'
    AND CAST(b.order_date AS DATE) BETWEEN '01/10/2020' AND '03/10/2020'

输出是这样的:

File No Order Id    Test
-----------------------------------
33926   2000001001  SEMEN ANALYSIS
33900   2000001002  AMMONIA
33966   2000001044  TSH
33966   2000001044  PROLACTIN
33967   2000001045  HGB 
33967   2000001045  Pregnancy Test in Blood (SERUM)
33967   2000001045  H. PYLORI (Serum Ab) 
34000   2000001079  BACTERIAL CULTURE AND ANTIBIOTIC SENSITIVITY
34001   2000001080  BACTERIAL CULTURE AND ANTIBIOTIC SENSITIVITY
34002   2000001081  BACTERIAL CULTURE AND ANTIBIOTIC SENSITIVITY
34003   2000001082  BACTERIAL CULTURE AND ANTIBIOTIC SENSITIVITY
34020   2000001100  FSH
34020   2000001100  LH
34020   2000001100  TSH
34020   2000001100  PROLACTIN

但是我需要将每个订单 ID 的输出放在一行中,并且测试名称出现在一行中,而不是像这个示例订单 ID 2000001100 这样的多行输出我需要这样的输出:

34020   2000001100   FSH , LH , TSH , PROLACTIN 

我怎样才能在 SELECT 语句中做到这一点?

标签: sqlsql-serverstringdatetimewhere-clause

解决方案


您似乎想要字符串聚合。如果您运行的是 SQL Server 2017 或更高版本,则可以使用string_agg()

select p.patient_no as file_no, lo.order_id, string_agg(lt.testname, ', ') as testnames
from patients p
inner join lab_orders lo on  p.patient_no = lo.patient_no 
inner join customers c on lo.custid = c.custid
inner join order_details od on lo.order_id = od.order_id 
inner join labtests lt on od.testid = lt.testid
where
    c.CustId > 1
    and cast(lo.order_date as time) between '01:00:00' and '23:50:50'
    and cast(lo.order_date as date) between '20201001' and '20201003'
group by p.patient_no, lo.order_id

重要笔记:

  • 始终使用显式、标准连接而不是老式(使用on关键字)、隐式连接(在 from 子句中使用逗号):这种几十年来的语法不应该在新代码中使用

  • 有意义的表别名使查询更易于编写和阅读

  • 不要对列别名或其他标识符使用单引号;它们仅用于文字字符串

  • YYYYMMDD是 SQL Server 中最便携的日期格式,无论区域设置如何都可以使用


推荐阅读