I'm trying to write a query in SSMS that can output a selection of Attributes as individual columns, with the keyword value for each attribute as the row value. I found code for a procedure in Shared reports (LP_BSO_LIST_ATTRIBUTES_NEW) that seems to be doing this based on the example output, but I don't quite understand how!
I'm currently using this, but it returns duplicate lines, with one row per Attribute column. Any thoughts on how to write this so that I'm only returning one row per constituent, with the Attributes all returned in the same row?
SELECT DISTINCT k.customer_no , c.sort_name , c.fname , c.lname , c.last_gift_dt , c.last_ticket_dt , case when k.keyword_no IN (533, 532) then k.key_value else NULL end AS 'Attribute 1' , case when k.keyword_no = 534 then k.key_value else NULL end AS 'Attribute 2'FROM T_CUSTOMER cJOIN T_LIST_CONTENTS l on l.customer_no = c.customer_noJOIN TX_CUST_KEYWORD k on k.customer_no = c.customer_noWHERE l.list_no = 8340 and k.keyword_no IN (532, 533, 534)ORDER BY customer_noThe store procedure from BSO has a selection statement that looks like this:
SELECT cus.customer_no, [dbo].FS_CONST_STRING_NEW(cus.customer_no, 'Y') as const, kwd.description as attribute, case when kwd.data_type = @date_data_typ then CAST(CAST(cky.key_value as DATE) as varchar) else cky.key_value end as att_value, cus.sort_name FROM T_CUSTOMER cus left join TR_NAMESTATUS sts on cus.name_status = sts.id join TX_CUST_KEYWORD cky on cky.customer_no = cus.customer_no join T_KEYWORD kwd on kwd.keyword_no = cky.keyword_no join TR_CUST_TYPE cty on cus.cust_type = cty.id join dbo.FT_SPLIT_LIST(@attribute_list,',') par on kwd.keyword_no = par.element Any insight on how that is returning one key_value per column, across multiple columns? Or is that all being done in report setup?Thank you!
Hello Lily,
I agree with Sara, it looks like the query can return multiple lines per customer which would mean that the report is probably built around a column group.
What you could do if you are trying to do a query is use a dynamic pivot, a normal pivot if you know how many columns you will need in total, or, if you know exactly what specific attributes you will be needing for this query (and it looks like you might), you could basically just use nested queries as tables and then just group and coalesce the null column values into a single row per customer.
John