【问题标题】:How to write these two (ANSI) SQL queries?如何编写这两个(ANSI)SQL 查询?
【发布时间】:2009-12-18 18:58:47
【问题描述】:

我有一个表格,其中的数据如下所示:

create table demo_patient_info (
  attend timestamp,  
  patient_id int, 
  blood_pressure double
);

我想编写(最好是 ANSI)SQL 查询,允许我执行以下操作:

查询1:

返回所有患者的bp之间的差值(使用WHERE子句限制笛卡尔积返回的行数)

查询2:

返回每个患者的 bp 与表中一位特定(即指定)患者的 bp 之间的差异

【问题讨论】:

  • "blood_pressure double" 不是故意的?!
  • 呵呵...弗洛伊德的失误...zing!

标签: sql


【解决方案1】:

1)

SELECT 
    t1.patient_id
   ,t2.patient_id
   ,t1.blood_pressure - t2.blood_pressure as bp_diff
FROM
   demo_patient_info t1
CROSS JOIN
   demo_patient_info t2
WHERE
   t1.patient_id < t2.patient_id

2)

SELECT 
    t1.patient_id
   ,t2.patient_id
   ,t1.blood_pressure - t2.blood_pressure as bp_diff
FROM
   demo_patient_info t1
CROSS JOIN
   demo_patient_info t2
WHERE 
   t2.patient_id = 1

这可能会为每个匹配提供两行,这可能会也可能不会

编辑:WHERE t1.patient_id &lt; t2.patient_id 在查询 1 中是为了防止跟随、重复和自匹配

ID1 ID2  diff 
1    2    1.4 
2    1    1.4 
1    1     0 

感谢 Jonathan Leffler 的提示 :)

【讨论】:

  • 纯 SQL 诗歌。我还没试过。但它在美学上令人愉悦(如果有道理的话)
  • 不确定我是否理解。为什么它会为每场比赛提供两行?假设它确实如此,我可以不使用 SELECT DISTINCT 来确保行是唯一的吗?
  • CROSS JOIN 应该使用条件过滤 - 通常 t1.patient_id
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
相关资源
最近更新 更多