Home > Net >  Query to segregate multiple data which is inserted into single column
Query to segregate multiple data which is inserted into single column

Time:02-01

There is a machine which is made with multiple parts, those parts were of two different country, the need is to find percentage of parts used from each country.

Machine Parts_Used % of IN part % of CH parts
M_001 IN_001, CH_001, IN_002, CH002, IN_003, IN_004, IN_005,
M_002 IN_0011, CH_0011, IN_0012, CH0012, CH_0013, CH_0014, Ch_001
select count(*) as "% of CH parts"
from tablename
where Parts_Used like 'CH%';

Used this but did not get result.

CodePudding user response:

Try this:

SELECT MP.[Machine]
      ,SUM(IIF(CHARINDEX('IN_', PU.[value]) > 0, 1, 0)) * 100.0 / COUNT(*) AS [% of IN part]
      ,SUM(IIF(CHARINDEX('CH_', PU.[value]) > 0, 1, 0)) * 100.0 / COUNT(*) AS [% of CH parts]
FROM machine_parts MP
CROSS APPLY STRING_SPLIT (Parts_Used, ',') PU
GROUP BY MP.[Machine]

enter image description here

The idea is to perform split of the values to now how may parts we have and easily perform the conditional counting with SUM and IIF. Basically, we have the following:

SELECT *
FROM machine_parts MP
CROSS APPLY STRING_SPLIT (Parts_Used, ',') PU

enter image description here

Then just counting.

  • Related