2013-12-09 116 views
0

我試圖做一個報告,我有一些dificulty設計查詢來顯示我需要的數據。返回一定數量的行滿足一定條件的值的查詢

我有2個表:

+-----------+------------+----------+ 
+TherapyID + CostumerID + ClinicID + 
+-----------+------------+----------+ 
+ 1  + John  + Clinic 1 + 
+-----------+------------+----------+ 
+ 2  + Susan  + Clinic 2 + 
+-----------+------------+----------+ 
+ 3  + Mary  + Clinic 3 + 
+-----------+------------+----------+ 


+-----------+--------------+-----------+--------+ 
+TherapyID + TherapyLine + Treatment + Result + 
+-----------+--------------+-----------+--------+ 
+  1  +  1  +  A  + Success+ 
+-----------+--------------+-----------+--------+ 
+  1  +  2  +  B  + Success+ 
+-----------+--------------+-----------+--------+ 
+  1  +  3  +  C  + Success+ 
+-----------+--------------+-----------+--------+ 
+  2  +  1  +  A  + Success+ 
+-----------+--------------+-----------+--------+ 
+  2  +  2  +  B  + Fail + 
+-----------+--------------+-----------+--------+ 
+  2  +  3  +  C  + Success+ 
+-----------+--------------+-----------+--------+ 
+  3  +  1  +  A  + Success+ 
+-----------+--------------+-----------+--------+ 
+  3  +  2  +  B  + Success+ 
+-----------+--------------+-----------+--------+ 
+  3  +  3  +  C  + Fail + 
+-----------+--------------+-----------+--------+ 

我需要做一個查詢,顯示已成功接收到的所有治療一個我只有客戶或therapyid的,B,C

查詢結果應該是這樣的:

+------------+-------------+----------+---------+-----------+---------+ 
+ TherapyID + TherapyLine + Customer + Clinic + Treatment + Result + 
+------------+-------------+----------+---------+-----------+---------+ 
+  1  +  1  + John + Clinic 1+ A  + Success + 
+------------+-------------+----------+---------+-----------+---------+ 
+  1  +  2  + John + Clinic 1+ B  + Success + 
+------------+-------------+----------+---------+-----------+---------+ 
+  1  +  3  + John + Clinic 1+ C  + Success + 
+------------+-------------+----------+---------+-----------+---------+ 

這是唯一therapyid所有治療A,B, ç其中成功 我真的沒有對如何查詢這個任何想法,我曾嘗試到現在 八方通返回從TherapyID * 2,3 *,其中結果是成功太結果。 Thx提前尋求幫助。

+0

它是一個奇裝異服的診所?並考慮提供適當的DDL(和/或sqlfiddle)。 – Strawberry

+0

如果'TheraphyID 1'處理結果中失敗的'D',那麼只要它具有'A,B,C'並且它成功了,它是否仍然會包含在列表中? –

+0

不,在這種情況下它不應該返回任何內容。 – user31469

回答

0
select t1.TherapyID,TherapyLine,t1.CostumerID as Customer,Clinic,Treatment, 
Result from table1 t1,table2 t2 where t1.TherapyID =t2.TherapyID and 
t2.result='Success' group by customerID having count(customeID)=3 
0
SELECT t1.TherapyID,TherapyLine,CustomerID as Customer,ClinicID as Clinic,Treatment,Result 
FROM FROM t1 JOIN t2 ON t1.TherapyID=t2.TherapyID WHERE CustomerID IN 
(SELECT CustomerID 
FROM t1 JOIN t2 ON t1.TherapyID=t2.TherapyID AND Result='Success' 
GROUP BY CustomerID 
HAVING COUNT(CustomerID)=3)