SQLデータベースからデータ抽出を構築しています。私は複数のテーブルから特定の列を選択する次のSQLクエリを持っています。問題のある関係はこれです: OTPSaleテーブルへの外部キーを持つConveyancingDetailテーブルへの外部キーを持つConveyancingConditionテーブルがあります。 OTPSaleのレコードは、複数のConveyancingConditionレコードを持つ1つのConveyancingDetailレコードを持つことができます。SQL複数のテーブルから選択グループ化する
ConveyancingConditionフィールドを別々に選択し、それらを1つの文字列に結合する必要があります。
私が選択を実行すると、同じOTPSaleに対して複数のレコードが受信されます。私はconveyancingDetailでグループ化する必要があることを知っていますが、集計関数またはGROUP BY句のいずれにも含まれていないため、列が選択リストで無効です。私はあまりにも多くのフィールドを選択して、それらをすべて(少なくとも50の異なる列)グループに追加します。
これを行う正しい方法は何ですか?
select distinct
--other fields from other tables
(select FORMAT(conveyancingCondition.DateRequired, 'dd/MM/yyyy')
where conveyancingCondition.Name = 'Deposit') 'Deposit Date Required',
(select FORMAT(conveyancingCondition.DateRequired, 'dd/MM/yyyy')
(select FORMAT(conveyancingCondition.DateRequired, 'dd/MM/yyyy')
where conveyancingCondition.Name = 'Subject') 'Subject To Sale Date Required',
(select FORMAT(conveyancingCondition.DateRequired, 'dd/MM/yyyy')
where conveyancingCondition.Name = 'Guarant') 'Guarantee Date Required',
ISNULL(stuff((SELECT (',' + conveyancingCondition.DateRequired) FROM otp.ConveyancingCondition cd where (cd.ConveyancingDetailId = conveyancingDetail.Id AND cd.IsApplicable=1) FOR XML PATH('')), 1, 1, ''), NULL) as 'ConditionDates'
from otp.OTPSale
left join otp.ConveyancingDetail conveyancingDetail
on conveyancingDetail.Id = otp.OTPSale.ConveyancingDetailId
left join otp.ConveyancingCondition conveyancingCondition
on conveyancingCondition.ConveyancingDetailId = conveyancingDetail.Id
WHERE otp.OTPSale.IsTransferRequired= 1
--group by conveyancingDetail.Id
データは次のようになります。
OTPSale
Id ConveyancingDetail IsTransferRequired
1 1 1
2 2 1
ConveyancingDetail
Id
1
2
3
ConveyancingCondition
Id ConveyancingDetailId Name IsApplicable DateRequired
1 1 Deposit 1 2016-09-12
2 1 Bond 1 2016-09-26
3 1 Subject 1 2016-09-26
4 1 Guarant 1 2016-09-30
5 1 Other 0 NULL
6 2 Deposit 1 2016-09-15
7 2 Bond 1 2016-09-16
8 2 Subject 1 2016-09-17
9 2 Guarant 1 2016-09-18
10 2 Other 0 NULL
これは私が
OTPSaleId Deposit Date Required Bond Date Required Subject Date Required Guarantee Date Required Other ConditionDates
1 2016-09-12 2016-09-26 2016-09-26 2016-09-30 NULL 2016/09/22, 2016/09/26, 2016/09/26, 2016/09/30
2 2016-09-15 2016-09-16 2016-09-17 2016-09-18 NULL 2016/09/16, 2016/09/16, 2016/09/17, 2016/09/18
を試してみてください?期待するものですか'mysql'、' postgresql'、 'sql-server'、' oracle'、 'db2'のどれかを指定するタグを追加してください。 –
おっと、忘れてしまった、SQLサーバー - タグに追加 –