I have the following query which gives the intended results but I am having trouble with using CAST to change the date formatting to mm/dd/yyyy
.
Original code:
SELECT
owneridname,
DATEADD(week, DATEDIFF(week, 0, createdon), 0) [week],
COUNT(svb_contactname) AS [Yes],
COUNT(*) - COUNT(svb_contactname) AS [No]
FROM incident
WHERE createdon >= DATEADD(day, -15, GETDATE())
GROUP BY
owneridname,
DATEADD(week, DATEDIFF(week, 0, createdon), 0)
ORDER BY
Week DESC;
Results:
owneridname | week | Yes | No |
---|---|---|---|
John Smith | 2023-06-26 00:00:00.000 | 3 | 0 |
Alexis Smith | 2023-06-26 00:00:00.000 | 0 | 12 |
Andrea Smith | 2023-06-26 00:00:00.000 | 0 | 22 |
Ashley Smith | 2023-06-26 00:00:00.000 | 0 | 4 |
I tried DATEADD(week, DATEDIFF(week, 0, CAST(createdon as date)), 0) [week]
in the SELECT statement and separately CAST(DATEADD(week, DATEDIFF(week, 0, createdon), 0) as date)
under GROUP BY but I receive error messages on both.
3条答案
按热度按时间dldeef671#
Try this:
This query does not attempt to format date/time as text: doing-so in SQL is an anti-pattern.
The formatting of dates, numbers, etc, is a presentation-layer concern.
Instead, this query preserves the numeric values needed to group by week: the year-number and the week-number: you can reconstitute the first-date-of-weeek in a later CTE step.
Using text values for
GROUP BY
will always because it means there'll be string allocations, copies, and more going-on inside the DB engine - not to mention being just plain wrong fordate
values: usingMM/dd/yyyy
is particularly egregious because you cannot meaningfully lexicographically sortMM/dd/yyyy
dates anyway.Additionally, this query puts the
GROUP BY
aggregation step into a separate named CTE (aggregatedByOwnerId
), which also means you can inspectpastFortnightIncidents
independently - and re-use those CTE steps separately.But my main reason for putting the
GROUP BY
separately is to help with the common misconception in SQL that theSELECT
clause is somehow evaluated beforeGROUP BY
(fun-fact: it isn't).A common tarpit in SQL is trying to do too much in the
SELECT
clause, especially withGROUP BY
.Anyway...
7jmck4yq2#
The solution I found was to wrap
CAST()
around theDATEADD
call in both theSELECT
andGROUP BY
statement, which a fellow SOer advised.imzjd6km3#
Format function may help you,
Updated query,