I have to create a MS SQL Query on the table below.
Consider I have following single table:
I want to get the following result by grouping on column1:
How can I accomplish this?
I have to create a MS SQL Query on the table below.
Consider I have following single table:
I want to get the following result by grouping on column1:
How can I accomplish this?
Use COUNT
with GROUP BY
.
Query
SELECT column1, 'N/A' as column2, 'N/A' as column3,
COUNT(column1) AS column4_amount
FROM your_table_name
GROUP BY column1;
SELECT column1, 'N/A' as column2, 'N/A' as column3, COUNT(1) AS column4_amount
FROM table_name
GROUP BY column1
if you don't need column2 and column3 then try below:
SELECT column1, COUNT(1) AS column4_amount
FROM table_name
GROUP BY column1
Update: As you want results which has more than one occurrence, try this:
SELECT column1, 'N/A' as column2, 'N/A' as column3, COUNT(1) AS column4_amount
FROM table_name
GROUP BY column1
HAVING COUNT(1) > 1
You should use GROUP BY
with column1 as GROUP BY
helps you group all the items with the same name.
To count total items under a group of items, from the table with the same name, use the COUNT
aggregate function. Now you need to check that each item exists more than once. Use the HAVING
clause which takes all the groups that have more than two items.
SELECT column1, 'N/A' as column2, 'N/A' as column3, COUNT(1) AS column4_amount
FROM your_table_name
GROUP BY column1
HAVING COUNT(1) > 1