Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This should do:</p> <pre><code>SELECT PT.[DESCRIPTION] as [Transaction Type], SUM(P.ORIGINAL_AMOUNT) as [AMOUNT (£) CREDIT], SUM( CASE WHEN PR.[Description] = 'Product type 1' THEN P.ORIGINAL_AMOUNT END) [Product 1 (£)], SUM( CASE WHEN PR.[Description] = 'Product type 2' THEN P.ORIGINAL_AMOUNT END) [Product 2 (£)], SUM( CASE WHEN PR.[Description] = 'Product type 3' THEN P.ORIGINAL_AMOUNT END) [Product 3 (£)] FROM [X].[dbo].[PAYMENT] P join [X].[dbo].[TABLE1] PT on P.PAYMENT_ID=PT.PAYMENT_TYPE_ID join [X].[dbo].[TABLE2] SO on SO.PAYMENT_TYPE_ID=P.PAYMENT_TYPE_ID join [X].[dbo].[TABLE3] OI on OI.ORDER_ID=SO.SITE_ORDER_ID join [X].[dbo].[TABLE4] PR on PR.Product_id=OI.PRODUCT_ID GROUP BY PT.[DESCRIPTION] </code></pre> <p><strong>UPDATED</strong> Well, since you need a dynamic number of columns, you will need dynamic SQL (as njk said). I'll post one way to do this with <code>PIVOT</code>, though it need SQL Server 2005+.</p> <pre><code>DECLARE @ProductTypes AS NVARCHAR(MAX), @Query AS NVARCHAR(MAX); SELECT @ProductTypes = STUFF((SELECT DISTINCT ',' + QUOTENAME([Description]) FROM [X].[dbo].[TABLE4] FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') SET @Query = ' ;WITH CTE AS( SELECT PT.[description] AS [Transaction Type], Sum (P.original_amount) AS [AMOUNT (£) CREDIT], PR.[description] AS [Product Type] FROM [X].[dbo].[payment] P JOIN [X].[dbo].[table1] PT ON P.payment_id = PT.payment_type_id JOIN [X].[dbo].[table2] SO ON SO.payment_type_id = P.payment_type_id JOIN [X].[dbo].[table3] OI ON OI.order_id = SO.site_order_id JOIN [X].[dbo].[table4] PR ON PR.product_id = OI.product_id GROUP BY PT.[description], PR.[description] ) SELECT * FROM CTE AS T PIVOT(SUM([AMOUNT (£) CREDIT]) FOR [Product Type] IN ('+@ProductTypes+')) AS PT' EXEC(@Query) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload