【问题标题】:How to write a query to get data count with combination of codision如何编写查询以结合编码获取数据计数
【发布时间】:2018-04-25 08:53:31
【问题描述】:

我有两个名为 [DrugPrescriptionEdition] 和 [PrescriptionDoseDetail] 的表,现在,我使用以下查询连接这两个表并获取结果集。

select * from   DrugPrescription dp where id in(
  SELECT   distinct  dpe.template
  FROM [DrugPrescriptionEdition] dpe
  join PrescriptionDoseDetail pdd on pdd.prescription = dpe.id 
   where doseEnd_endDate is NULL and doseEnd_doseEndType =1
   )

但现在我想记录只包含,(1,2) 'datasource' 列和处方的组合。id 应该是相同的。

示例:像记录 {处方ID =4 并且包含 ,(1,2) }。我不会考虑,只有 1 或 2 包含记录。

需要一些专家的帮助才能将此条件添加到我的上述查询中并进行修改。

预期结果:我需要过滤掉,上面的查询结果使用这个,新的条件也是。

【问题讨论】:

  • 您能否提供一些样本数据和使用该数据的预期结果?
  • @DT 添加草稿我预期的结果。
  • 我对你的问题感到困惑。您显示具有多个表的查询。然后显示一个表格。
  • @GordonLinoff,我使用了多个表格,我放了 3 张草稿图片,来解释我的期望......!!!对我来说很难解释,没有草稿可视化。

标签: sql sql-server database join


【解决方案1】:

让我假设您的记录在一个表中。这是一种方法:

select t.*
from t
where (t.dataSource = 1 and
       exists (select 1 
               from t t2
               where t2. prescriptionid = t.prescriptionid and
                     t2.dataSource = 2
              )
      ) or
      (t.dataSource = 2 and
       exists (select 1 
               from t t2
               where t2.prescriptionid = t.prescriptionid and
                     t2.dataSource = 2
              )
      );

尚不清楚是否允许任何其他数据源。如果不是,则添加:

and
not exists (select 1
            from t t3
            where t3.prescriptionid = t.prescriptionid and
                  t3.dataSource not in (1, 2)
           )

【讨论】:

    猜你喜欢
    • 2016-06-07
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多