Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

sum of two count( columns)

Status
Not open for further replies.

kandhi17

Vendor
Mar 23, 2006
2
US
could any one kindly help me for writing a query for

sum of two columns with count from same table.

ex: quantity1, quantity2
sum(count(quantity1), count(quantity2))
 
sum of two columns with count from same table"

????????

You may simply add the two counts in an expression.
Code:
SELECT widget_name, SUM(qty_delivered) + SUM(qty_backordered)
FROM WidgetOrders
GROUP BY widget_name

This would give for each widget the number delivered plus the number on backorder. Presumably that would be the number ordered.


Possibly you wish to count the number of orders for a widget.
Code:
SELECT widget_name, SUM(qty_delivered) + SUM(qty_backordered), COUNT(*)
FROM WidgetOrders
GROUP BY widget_name


Possibly you wish to count the number of orders with deliveries and the the number of orders with backorders.
Assuming the value of qty_backordered is zero if nothing is backordered and the value of qty_delivered is zero if nothing is delivered.
Code:
SELECT widget_name, 
       SUM(qty_delivered) + SUM(qty_backordered), 
       COUNT(*), 
       SUM(CASE
             WHEN qty_delivered = 0 THEN 0
             ELSE 1
           END),
       SUM(CASE
             WHEN qty_backordered = 0 THEN 0
             ELSE 1
           END)
FROM WidgetOrders
GROUP BY widget_name



 
thanks for replying, but i would like to count the column1 and column2 individually and then sum of column1, column2.

i will appreciate if you could reply me back again
 
What do you mean by counting column1?

In general we count rows. Either all of the rows with COUNT(*) or the rows which are not NULL with COUNT(column_name).
 
If you wish to have the separate counts of NOT NULL rows then list each one in the SELECT list.
Code:
SELECT COUNT(colA), COUNT(colB), COUNT(colA) + COUNT(colB)
...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top