In a table I have 2 versions of cust_id per client; what I am trying to achieve is a list of those products which are only listed under one version of the cust_id to fix the differences and output a report. I do understand that the distinct won't work because I might have the same product for multiple cust_id's.
Am trying to use DISTINICT on one column only to get a list of the distinct product_name for all cust ids.
SELECT *
FROM (
SELECT DISTINCT
([product_name]),
[cust_id] % 100000 AS 'CustId',
COUNT([cust_id]) AS 'CustIdCount'
FROM [dbo].[solars_solutions_setting]
WHERE [cust_id] IS NOT NULL
GROUP BY
[product_name],
[cust_id] % 100000,
[value]
) AS Settings WHERE Settings.CustIdCount < 2
Is it possible to output a result having three columns?
Given that you are using SQL Server 2017, we can take advantage of STRING_AGG
here:
SELECT
product_name,
STRING_AGG(cust_id, ',') AS cust_ids,
COUNT(DISTINCT cust_id) AS dist_cust_cnt
FROM [dbo].[solars_solutions_setting]
GROUP BY
product_name
HAVING
COUNT(DISTINCT cust_id) > 1;
I chose to retain product names where there be more than one cust_id
present. In this case, the CSV list cust_ids
would have more than one value. Otherwise, it would only have a single value and the call to STRING_AGG
would not serve much purpose.
string_agg
is available in this sql sever version.
SELECT *
FROM (
SELECT DISTINCT
([product_name]),
[cust_id] % 100000 AS 'CustId',
COUNT([cust_id]) AS 'CustIdCount',
string_agg(cust_id, ',') as listCust
FROM [dbo].[solars_solutions_setting]
WHERE [cust_id] IS NOT NULL
GROUP BY
[product_name],
[cust_id] % 100000,
[value]
) AS Settings WHERE Settings.CustIdCount < 2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.