0

I have a flat text file data which I import into a SQL Server table.

It creates and table with specified name along with multiple columns as per data file.

Now I need a query which will return the data and its count. e.g.

data file :

BREAD,MILK
BREAD,DIAPER,BEER,EGGS
MILK,DIAPER,BEER,COKE
BREAD,MILK,DIAPER,BEER
BREAD,MILK,DIAPER,COKE 
BREAD,ICE,MANGO
JUICE,BURGER

Result should be

BREAD | 5
MILK  | 4
DIAPER| 4

and so on.

6
  • What is the schema of your table? Commented Apr 21, 2010 at 14:42
  • Are you effectively creating 1 row with n columns? Commented Apr 21, 2010 at 14:43
  • That's the problem with not normalized databases, everything gets more difficult. Commented Apr 21, 2010 at 14:44
  • @Otavio: we don't know if the database is denormalized or not. The data could be transformed in any number of ways during import. Commented Apr 21, 2010 at 14:45
  • Why don't BEER, EGGS, etc. show up in the output? Commented Apr 21, 2010 at 14:46

2 Answers 2

1

At a guess at the requirement as would need to see your scheme, but, maybe something like this?

SELECT
    ItemValue,
    COUNT(*)
FROM
(
    SELECT
        Column1 ItemValue
    FROM
        DataTable
    UNION ALL
    SELECT
        Column2 ItemValue
    FROM
        DataTable
    UNION ALL
    SELECT
        Column3 ItemValue
    FROM
        DataTable
    UNION ALL
    SELECT
        Column4 ItemValue
    FROM
        DataTable
) UnionDataTable
Sign up to request clarification or add additional context in comments.

1 Comment

UnionDataTable is an Alias for the previous SELECT.
0

This is a wild guess based on incomplete information:

select Item, count(*)
from Items
group by Item

1 Comment

Do you think I can achieve this using cursor or similar, because I don't know how much columns would be for different data files?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.