I have a query that checks a database for multiple customer barcode scans in a single day. This report works great, however I’d like to add another piece to it. I would like to include a column “Times Scanned” to the output. However, since i’m using “SUM” it won’t list multiple times on 1 line. For example if barcode “1234” is found to be scanned twice, I want the times it was scanned (tickets.dtcreated) to be listed in the “times Scanned” column as one output.
Here is my current Output:
Barcode DtCreatedDate Number of Scans
1234 1/1/2013 2
1235 1/1/2013 2
1563 1/2/2013 3
Here is what I want my output to look like (Keep in mind the “Times Scanned” should only show the times on the day that multiple scans took place (DTcreateddate):
Barcode DtCreatedDate Number of Scans Times Scanned
1234 1/1/2013 2 11:15AM, 12:15PM
1235 1/1/2013 2 9:00AM, 4:00PM
1563 1/2/2013 3 8:05AM, 8:08AM, 5:50PM
My Current Query is Below
SELECT Customers.sBarcode, CAST(FLOOR(CAST(Tickets.dtCreated AS FLOAT)) AS DATETIME) AS dtCreatedDate, COUNT(Customers.sBarcode) AS [Number of Scans]
FROM Tickets INNER JOIN
Customers ON Tickets.lCustomerID = Customers.lCustomerID
WHERE (Tickets.dtCreated BETWEEN @startdate AND @enddate) AND (Tickets.dblTotal <= 0)
GROUP BY Customers.sBarcode, CAST(FLOOR(CAST(Tickets.dtCreated AS FLOAT)) AS DATETIME)
HAVING (COUNT(*) > 1)
ORDER BY dtCreatedDate
You can’t use
SUMfor this, but you can useFOR XML PATH. Add this to your SELECT list:The idea here is to use
RIGHT(convert(varchar, sub.dtCreated, 100), 7)to get the formatted time, and then concatenate them usingFOR XML PATH, while removing the leading comma withSTUFF