Question

Have a bit of an issue here and I for some reason can't find a simple way to do this even though I know there has to be. We have the ability to get total sales between dates, but my boss wants to be able to get the total sales per day of the week, so for example, total of all sales on Mondays between 7/1/13 and 8/1/13.

Here is the query for summing the sales between those dates.

SET NOCOUNT ON
SET CONCAT_NULL_YIELDS_NULL OFF

SELECT tblItem.dateOrder,
    tblMerchPack.strMerchPackCategory + tblPayTypeID.strPayTypeName AS strMerchPackCategory,
    tblMerchPack.strMerchPackID,
    tblMerchPack.strMerchPackName + tblPayTypeID.strPayTypeName AS strMerchPackDescription,
    tblMerchItem.strMerchItemID,
    tblMerchItem.strMerchItemName + tblPayTypeID.strPayTypeName AS strMerchItemDescription,
    tblItem.lngQuantity,
    tblItem.curPrice,
    tblItem.curPriceDiscount,
    tblItem.curTaxA,
    tblItem.curTaxB,
    tblPay.curTender - tblPay.curChange AS curPayment,
    tblStoredValue.curCash AS curStoredPayment,
    CASE 
        WHEN tblItem.lngMerchItemID IS NULL
            THEN - 1
        WHEN tblItem.lngMerchItemID > 0
            THEN 0
        WHEN tblPayTypeID.lngPayTypeID IS NULL
            THEN 1000
        WHEN tblPayTypeID.lngPayTypeID > 0
            THEN tblPayTypeID.lngPayTypeID
        ELSE - 1
        END AS 'lngPaymentSort'
FROM tblItem
LEFT JOIN tblPay ON tblItem.lngItemID = tblPay.lngItemID
LEFT JOIN tblStoredValue ON tblItem.lngItemID = tblStoredValue.lngItemID
LEFT JOIN tblPayTypeID ON tblPay.lngPayTypeID = tblPayTypeID.lngPayTypeID
LEFT JOIN tblMerchItem ON tblItem.lngMerchItemID = tblMerchItem.lngMerchItemID
LEFT JOIN tblMerchPack ON tblItem.lngMerchPackID = tblMerchPack.lngMerchPackID
WHERE (
        tblItem.dateOrder BETWEEN '7/1/2013 5:00:00 AM'
            AND '8/1/2013 4:59:59 AM'
        )
ORDER BY lngPaymentSort,
    strMerchPackCategory,
    strMerchItemDescription
Was it helpful?

Solution

If you want to /just/ get the results for Mondays, then just add the following to your where clause:

and datepart(dw,tblItem.dateOrder) = 1

If you want the query to contain a column for each day you'll have to use a case statement in the select part using the datepart for each day.

This is assuming that you're in the US.. the first day of the week varies by country

DatePart info - http://msdn.microsoft.com/en-us/library/ms174420.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top