Question : How Do I Deal with Null Values in SQL Pivot Queries

I am running a query to get a monthly summary of sales by customer using pivot in SQL 2008.  My problem is that when I try to add monthly results for a total in Coldfusion, I get errors due to null values.  SQL doesn't allow isnull in the pivot area, and it doesn't work in the data area since there are sometimes no sales in a month for a customer, so it never processes the month in order to convert the null value to zero.  I'd appreciate any advice on dealing with this on either the SQL or CF side.  Thanks

declare @rep int
set @rep = 999999

SELECT *
FROM(
  SELECT
      contacts.first_name + ' ' + contacts.last_name SalesPerson,
    YEAR(invoice_date) [Year],
    CASE MONTH(invoice_date)
      WHEN 1 THEN 'January'
      WHEN 2 THEN 'February'
      WHEN 3 THEN 'March'
      WHEN 4 THEN 'April'
      WHEN 5 THEN 'May'
      WHEN 6 THEN 'June'
      WHEN 7 THEN 'July'
      WHEN 8 THEN 'August'
      WHEN 9 THEN 'September'
      WHEN 10 THEN 'October'
      WHEN 11 THEN 'November'
      WHEN 12 THEN 'December'
    END as [Month],
    invoice_hdr.customer_id,
    customer.customer_name,
    isnull((total_amount - freight),0) total_amount
  FROM invoice_hdr(nolock)
            join customer(nolock) on invoice_hdr.customer_id = customer.customer_id
            join contacts(nolock) on contacts.id = invoice_hdr.salesrep_id
  WHERE year(invoice_date)  = 2010 and invoice_hdr.salesrep_id = @rep
) SalesSummary
PIVOT
(
  SUM(total_amount)
  FOR [Month] IN (
    [January],[February],[March],[April],
    [May],[June],[July],[August],
    [September],[October],[November],[December]
  )
) AS PivotTable
ORDER BY salesperson, customer_name, customer_id, [Year] desc

Answer : How Do I Deal with Null Values in SQL Pivot Queries

Hi learningunix,

the line checks if the left-most byte of 'num' is '1'.

'&num' is a pointer to the memory address where the first byte of 'num' resides. The '(char*)' casts this pointer '&num' (which is a pointer to int) to a pointer to char. Since char is a one byte data type accessing that 'pointer to char' with '*' accesses the first byte of the int. In little endian this byte has to be '1' for and 'int' which is '1' - in big endian the first byte would be '0' since the least significant byte is the most right one ...

Hope that helps,

ZOPPO

Random Solutions  
 
programming4us programming4us