Category Archives: SQL

Remove repeated column values for the report in SQL

Suppress the repeated column values for the report in SQL

Remove the repeated column values for the report in SQL Query like:

I fired the query in MariaDB and want to suppress or remove the duplicate customer name showing repeatedly to present the report in good manners:


select c.customerName,o.shippedDate ,o.orderNumber 
from classicmodels.orders o, classicmodels.customers c where o.customerNumber = c.customerNumber 
order by 1

customerName                      |shippedDate|orderNumber|
----------------------------------+-----------+-----------+
Alpha Cognac                      | 2003-07-06|      10136|
Alpha Cognac                      | 2003-11-10|      10178|
Alpha Cognac                      | 2005-04-01|      10397|
Amica Models & Co.                | 2004-08-19|      10280|
Amica Models & Co.                | 2004-09-14|      10293|
Anna's Decorations, Ltd           | 2003-09-15|      10148|
Anna's Decorations, Ltd           | 2003-11-09|      10169|
Anna's Decorations, Ltd           | 2005-01-25|      10370|
Anna's Decorations, Ltd           | 2005-03-15|      10391|

To Show like this, i have use the case statement with lag function as follows:

select (case c.customerName when LAG(c.customerName) over (order by c.customerName) then null else c.customerName end) as "CustomerName"
,o.shippedDate ,o.orderNumber 
from classicmodels.orders o, classicmodels.customers c where o.customerNumber = c.customerNumber 
order by c.customerName

CustomerName                      |shippedDate|orderNumber|
----------------------------------+-----------+-----------+
Alpha Cognac                      | 2005-04-01|      10397|
                                  | 2003-07-06|      10136|
                                  | 2003-11-10|      10178|
Amica Models & Co.                | 2004-08-19|      10280|
                                  | 2004-09-14|      10293|
Anna's Decorations, Ltd           | 2003-09-15|      10148|
                                  | 2003-11-09|      10169|
                                  | 2005-01-25|      10370|
                                  | 2005-03-15|      10391|

You can also use the decode statement:

select
decode( c.customerName,(lag(c.customerName, 1, null) over (order by  c.customerName)), null,c.customerName) as "customerName"
,o.shippedDate ,o.orderNumber 
from classicmodels.orders o, classicmodels.customers c where o.customerNumber = c.customerNumber 
order by 1

In Oracle, if using SQL PLUS then use Break

BREAK command tells SQL*Plus to print a column once, then wait for the column to change.  Each time the column changes, SQL*Plus will print the new value once after skipping the defined number of lines.

Break on CustomerName
select c.customerName,o.shippedDate ,o.orderNumber 
from classicmodels.orders o, classicmodels.customers c where o.customerNumber = c.customerNumber 
order by 1