简体   繁体   中英

T-SQL Get all years from - to

I am trying to find a lists with the sales of each Shop for each year from a database. But i want to print all years with 0 sales as well (for some years/shops there will be no data in my database)

I have done the following procedure but it only returns Years and shops which have non zero values .

SELECT   YEAR(temp.INVOICE_DATE) AS Year, Shop.Name, SUM(temp.QTY * Product.Price) AS Total
FROM    (
            SELECT  pci.INVOICE_ID, ci.STORE_ID, ci.INVOICE_DATE, pci.PRODUCT_ID, pci.QTY 
            FROM    [Product_Customer Invoice] pci, [Customer Invoice] ci
            WHERE   pci.INVOICE_ID = ci.INVOICE_ID
        )AS temp, Product, Shop
WHERE   Product.PRODUCT_ID = temp.PRODUCT_ID AND Shop.STORE_ID = temp.STORE_ID  
GROUP BY YEAR(temp.INVOICE_DATE), Shop.Name
ORDER BY Year ASC

I get The following result

在此处输入图片说明

I would like to ask for any ideas how to include 0 for years or shops that not any sales has been done

Use a cross join to generate the rows and then left join to bring in the data you want:

SELECT y.Year, s.Shop.Name,
       COALESCE(SUM(pci.QTY * p.Price), 0) AS Total
FROM Shop s CROSS JOIN
     (SELECT DISTINCT invoice_date as year FROM [Product_Customer Invoice]
     ) y LEFT JOIN
     [Product_Customer Invoice] pci
     ON YEAR(pci.invoice_date) = y.year AND
        pci.store_id = s.store_id LEFT JOIN
     Product p
     ON pci.PRODUCT_ID = p.PRODUCT_ID
GROUP BY y.year, s.name
ORDER BY y.year, s.name;

Notice that this also fixes your join syntax and removes the unnecessary subquery.

This assumes that all the years you want are in [Product_Customer Invoice] . If you want a different set of years, either explicitly list them using VALUES() , use a recursive CTE to generate them, or use a calendar table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM