1
我有這個sql用於通過連接3個表,sample_register,villages和water_cssr來獲取數據。SQL將表連接到其他表兩次
SELECT
sample_register.location,
sample_register.description,
villages.distance,
case when water_cssr.istp='Cs' then COUNT(water_cssr.usin) end as total_cs,
case when water_cssr.bdl='Y'and water_cssr.istp='Cs' then COUNT(water_cssr.usin) end as bdl_cs,
case when water_cssr.bdl='N'and water_cssr.istp='Cs' then min(water_cssr.activity) end as csmin,
case when water_cssr.bdl='N'and water_cssr.istp='Cs' then max(water_cssr.activity) end as csmax,
case when water_cssr.istp='Sr' then COUNT(water_cssr.usin) end as total_sr,
case when water_cssr.bdl='Y'and water_cssr.istp='Sr' then COUNT(water_cssr.usin) end as bdl_sr,
case when water_cssr.bdl='N' and water_cssr.istp='Sr' then min(water_cssr.activity) end as srmin,
case when water_cssr.bdl='N' and water_cssr.istp='Sr' then max(water_cssr.activity) end as srmax
FROM sample_register
LEFT JOIN villages on sample_register.location=villages.location
LEFT JOIN sample_allocation on sample_register.usin=sample_allocation.usin
INNER JOIN water_cssr ON water_cssr.usin = sample_register.usin
GROUP BY sample_register.location, sample_register.description, sample_allocation.cs
order by villages.dist_group, villages.location
我得到這樣
Location Type Distance Total_cs Bdl_cs Csmin csmax Total_sr Bdl_sr Srmin srmax A TYPE1 5 1 1 B TYPE2 10 1 1 4 12 B TYPE2 10 1 1 1 8 C TYPE3 15 1 1 9 14 C TYPE3 15 1 1 15 24 D TYPE1 10 1 1 E TYPE2 10 1 1 F TYPE1 20 1 1
在上述地點B中的結果和C有兩排,每排有一排具有價值在4至7列和另一排在第八值第11列。我想將這兩行的內容放在一行中,因爲第一列到第三列的值對於兩行都是通用的。例如連續兩個和三個組合應該產生一排這樣的
B TYPE2 10 1 1 4 12 1 1 1 8
請幫我重組SQL
爲什麼您sample_register.location,sample_register.description,sample_allocation.cs分組的全部三場小組嗎?哪一列導致第2行和第3行不被聚合? – RobP
sample_allocation.cs阻止聚合 – mansoondreamz
@Serpiton你說得對。但我的要求是獲取位置和描述的聚合,並在相應的列中顯示sr和cs的值。目前cs和sr的值在water_cssr表的同一列中,而另一列指定的值是cs或sr – mansoondreamz