sql - 如果有多个名称而不是多行 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 语句中做到这一点?
解决方案
您似乎想要字符串聚合。如果您运行的是 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 中最便携的日期格式,无论区域设置如何都可以使用
推荐阅读
- android - 有没有办法为这个标题工具栏问题找到解决方案?
- unity3d - 如何正确翻转有点复杂的 2D 角色?
- python - 如何在 numpy 中指定随机数生成器
- python - 如何修复循环错误一次跳过 1 个值?
- r - 当有大量观察值时,绘制直方图在一个条形图中显示一系列值
- c# - 如何在 Visual Studio 2015 中正确安装 Visual Basic Power Pack
- java - 有没有办法按跨度内容单击标签
- macos - Mac OS X v10.12.6 上的 GDB,程序以未知信号终止
- android - 传递 XML 可绘制数组并使用 Glide 获取它
- glsl - GLSL 着色器不需要的灰度效果