SQL嵌套选择与多行结果分组

时间:2018-04-11 17:45:06

标签: sql sql-server

希望这有道理..

我有以下数据库标签。 enter image description here

我正在尝试在SQL语句中将结果集组合在一起。

这是我当前的SQL语句:

SELECT 
    Patient.ID,
    Patient.Name,
    AnimalType.Value as AnimalType,
    Patient.Age,
    Customer.Firstname,
    Customer.Lastname

FROM Patient
    INNER JOIN Customer ON Patient.Owner_FK = Customer.ID
    INNER JOIN AnimalType ON Patient.Type_FK = AnimalType.ID

SELECT 
    Treatment.Treatment_Date,
    TreatmentType.Type
FROM Treatment
    INNER JOIN TreatmentItem ON Treatment.ID = TreatmentItem.Treatment_FK
    INNER JOIN TreatmentType ON TreatmentItem.TreatmentType_FK = TreatmentType.ID
    INNER JOIN Patient ON TreatmentItem.Patient_FK = Patient.ID
WHERE Patient.ID = 132

这有两个问题, 我有一个静态ID,结果是分开的。

这是上述SQL的结果 enter image description here enter image description here 我的问题是最后的结果集应该与相应的" Animal(患者)"一起使用。

但没有重复的数据。我可以一次性获取数据,但是我会有很多重复的数据行,只有TreatmentType不同......

那我该怎么做呢? 我搜索无济于事,并且无法制作一个正确的分组,这会使它工作。

它有意义吗? 它甚至可能吗?

期望结果的示例: enter image description here

1 个答案:

答案 0 :(得分:0)

我相信您可以通过单个查询,CASE语句和ROW_NUMBER()函数实现您的目标,但需要转换所有非文本列。

这是对潜在解决方案的粗略尝试(我没有构建您的数据库,所以我没有验证这个确切的SQL运行,但整体概念有效。)

WITH    CTE_PatientTreatments AS (
    SELECT 
        -- Get the row number for each treatment for a given patient
        ROW_NUMBER() OVER (PARTITION BY Patient.ID ORDER BY Treatment.ID) AS RowNum,
        Patient.ID,
        Patient.Name,
        AnimalType.Value as AnimalType,
        Patient.Age,
        Customer.Firstname,
        Customer.Lastname,
        Treatment.Treatment_Date,
        TreatmentType.Type
    FROM Patient
        INNER JOIN Customer ON Patient.Owner_FK = Customer.ID
        INNER JOIN AnimalType ON Patient.Type_FK = AnimalType.ID
        INNER JOIN TreatmentItem ON TreatmentItem.Patient_FK = Patient.ID
        INNER JOIN Treatment ON Treatment.ID = TreatmentItem.Treatment_FK
        INNER JOIN TreatmentType ON TreatmentItem.TreatmentType_FK = TreatmentType.ID
    WHERE Patient.ID = 132
    -- Ensure rows are sorted so that rows for the same patient are always together
    ORDER BY Patient.ID, Treatment.ID
)
-- Only display patient information for the first row
SELECT  -- Convert numeric columns to text so that the "ELSE ''" doesn't get coerced into a number (0)
        CASE WHEN (RowNum > 1) THEN '' ELSE CAST(ID AS VARCHAR) END AS ID,
        CASE WHEN (RowNum > 1) THEN '' ELSE Name END AS Name,
        CASE WHEN (RowNum > 1) THEN '' ELSE AnimalType END AS AnimalType,
        CASE WHEN (RowNum > 1) THEN '' ELSE CAST(Age AS VARCHAR) END AS Age,
        CASE WHEN (RowNum > 1) THEN '' ELSE Firstname END AS Firstname,
        CASE WHEN (RowNum > 1) THEN '' ELSE Lastname END AS Lastname,
        Treatment_Date,
        Type
FROM    CTE_PatientTreatments