使用不同WHERE子句连接两个表中的数据

时间:2012-10-11 03:28:09

标签: sql sql-server-2008

我需要在两个单独的表上执行各种联接/联合,以将我的结果合并到一个表中。首先,我将分享我拥有的和我需要的东西,然后我将分享我目前的非工作解决方案。

我有什么:

  • 每个表都包含一系列已执行的操作,每个操作都有opPatient(所有患者都有多个操作),opClassification(1,2,3或4),{ {1}},opDate

  • 查询的opPriceStart日期。

我需要什么:

使用以下内容生成单个表:

  • 所有不同End
  • 的列表
  • 每位患者:
    • 所有操作的总opPatients
    • 分类为4的所有操作的总opprice(分类4仅在opPrice中)
    • 所有操作的总数
    • 分类为3的操作总数
    • 分类为2的操作总数
  • 以上所有table2

当前的解决方案(显然不能正常工作)

  • 设置WHERE opDate >= @StartDate AND opDate <= EndDatestart日期(此处没有错误)

    end

非常感谢所有帮助,提示和指示!

谢谢! 真诚的,一个高速的编码员。

2 个答案:

答案 0 :(得分:0)

根据您的要求,似乎这就是您所需要的。

SELECT opPatient
, SUM(CASE WHEN opClassification = 1 THEN 1 ELSE 0 END) opC1
, SUM(CASE WHEN opClassification = 2 THEN 1 ELSE 0 END) opC2
, SUM(CASE WHEN opClassification = 3 THEN 1 ELSE 0 END) opC3
, SUM(CASE WHEN opClassification = 4 THEN 1 ELSE 0 END) opC4
, SUM(opPrice) AS TotalPrice
FROM
(
    SELECT * FROM Table1
    UNION ALL
    SELECT * FROM Table2
) AS NewTable
WHERE opDate >= @StartDate AND opDate <= @EndDate 
GROUP BY opPatient

答案 1 :(得分:0)

SET @StartDate = DATEADD(DAY, -(DATEPART(Day, @Date)-1), @Date);
SET @EndDate = DATEADD(DAY, -1, (DATEADD(MONTH, 1, @StartDate)));  

SELECT opPatient, 
    -- Totals
    COUNT(opPrice) AS OpsTotal, 
    SUM(opPrice) AS PriceTotal,
    SUM(CASE WHEN opDate >= @StartDate AND opDate <= EndDate THEN opPrice END) AS PriceThisMonth,
    -- Op 4
    SUM(CASE WHEN opClassification = 4 THEN 1 END) AS OpsOp4,
    SUM(CASE WHEN opClassification = 4 THEN opPrice END) AS PriceOp4,
    SUM(CASE WHEN opClassification = 4 AND opDate >= @StartDate AND opDate <= EndDate THEN opPrice END) AS Op4PriceThisMonth,
    -- Op 3
    SUM(CASE WHEN opClassification = 3 THEN 1 END) AS OpsOp4,
    SUM(CASE WHEN opClassification = 3 THEN opPrice END) AS PriceOp4,
    SUM(CASE WHEN opClassification = 3 AND opDate >= @StartDate AND opDate <= EndDate THEN opPrice END) AS Op4PriceThisMonth,
    -- Op 2
    SUM(CASE WHEN opClassification = 2 THEN 1 END) AS OpsOp4,
    SUM(CASE WHEN opClassification = 2 THEN opPrice END) AS PriceOp4,
    SUM(CASE WHEN opClassification = 2 AND opDate >= @StartDate AND opDate <= EndDate THEN opPrice END) AS Op4PriceThisMonth,

FROM (
    SELECT opPatient, opClassification, opDate, opPrice
    FROM Table1
    UNION ALL
    SELECT opPatient, opClassification, opDate, opPrice
    FROM Table1
)
GROUP BY opPatient