0

次の SQL コードは、1 つの行に請求書、もう 1 つの行にグループ化された支払いを含む 2 行のテーブルを作成します。ただし、それは望ましい表現ではありません。本当の目標は、請求書が一番上にあり、その後に日付順に並べられた支払いのリストが続く明細書として表示することです。

表示された情報に基づいて、それを達成するためのクエリを作成することは可能ですか? (詳細についてはお気軽にお問い合わせください)。誰でもアプローチを提案できますか?

SQLSELECTコードは次のとおりです。

SELECT     FilteredInvoice.accountidname,
           FilteredInvoice.createdon,
           FilteredInvoice.duedate,
           FilteredInvoice.invoicenumber,               
           FilteredInvoice.statecodename,
           FilteredInvoice.totalamount_base,
           FilteredMag_Payment.mag_paymentdate,
           FilteredMag_Payment.mag_amount_base,
           GETDATE() AS Today

FROM            FilteredInvoice
LEFT OUTER JOIN FilteredAccount ON FilteredInvoice.accountid = FilteredAccount.accountid
LEFT OUTER JOIN FilteredMag_Payment ON FilteredInvoice.invoiceid = FilteredMag_Payment.mag_invoiceid

WHERE     (FilteredInvoice.statecodename <> N'Canceled')
ORDER BY FilteredInvoice.createdon
4

2 に答える 2

0

元のクエリにはいくつかの奇妙な点があります。アカウント ID 名は、アカウント テーブルではなく、請求テーブルに実際に保持されているのでしょうか。Invoice から Account への左外部結合も、対応する Account のない Invoice が存在する可能性があるように見えます。特にステートメント レポートでは、その逆を想定するのがより一般的です。

元のクエリが必要なデータを正しく選択していると仮定すると、次のことをお勧めします。

SELECT    FilteredInvoice.accountidname, 
    FilteredInvoice.createdon,
    FilteredInvoice.createdon AS sort_date,
    FilteredInvoice.duedate,
    FilteredInvoice.invoicenumber,
    FilteredInvoice.statecodename, 
    FilteredInvoice.totalamount_base,
    CONVERT(datetime,NULL) AS mag_paymentdate,
    0 AS mag_amount_base,
    GETDATE() AS Today
FROM    FilteredInvoice 
LEFT OUTER JOIN    FilteredAccount ON FilteredInvoice.accountid = FilteredAccount.accountid 
WHERE    (FilteredInvoice.statecodename <> 'Canceled')
UNION ALL
SELECT    FilteredInvoice.accountidname, 
    FilteredInvoice.createdon,
    FilteredInvoice.createdon AS sort_date,
    FilteredInvoice.duedate,
    FilteredInvoice.invoicenumber,
    FilteredInvoice.statecodename, 
    FilteredInvoice.totalamount_base,
    FilteredMag_Payment.mag_paymentdate,
    FilteredMag_Payment.mag_amount_base,
    GETDATE() AS Today
FROM    FilteredInvoice 
LEFT OUTER JOIN    FilteredAccount ON FilteredInvoice.accountid = FilteredAccount.accountid 
JOIN    FilteredMag_Payment ON FilteredInvoice.invoiceid = FilteredMag_Payment.mag_invoiceid
WHERE    (FilteredInvoice.statecodename <> 'Canceled')
ORDER BY 3
于 2010-08-17T12:32:21.997 に答える
0

Looks to me like the payment info should be in the same row as the invoice. The only way you get a second row is if you have two payments. Since you are sorting on Invoice date, both rows will have the same date and sort next to each other.

My guess, from what you have said, is that you want to sort on Invoice Date if there isn't a payment and payment date if there is one. Try:

Order by Coalesce(FilteredMag_Payment.mag_paymentdate, FilteredInvoice.createdon)
于 2010-08-17T03:53:12.017 に答える