简体   繁体   中英

SQL - GROUP BY not working with DateName

I'm trying to extract how many times a particular thing happened on each day of the week. Here is what I tried:

SELECT Source , Event, Qty, DateName(WEEKDAY,( TranDate )) As DayOfWk
FROM OurDB
GROUP BY Source, Event, DateName(WEEKDAY,( TranDate )), Qty

But it isn't grouping by Source (which only has two possible values). If I take out the DateName function, then everything groups correctly. Basically I'm looking to get:

  • Source 1
    • Event 1
      • Monday - 15
      • Tuesday - 12
    • Event 2
      • Monday - 11
      • Thursday - 6
  • Source 2
    • Event 1
      • Monday ...etc

EDIT: Added row data

OurDB:

  • Source, Event, TranDate, Qty
  • Phone, Coupon 1, 7/2/15, 6
  • Internet, Coupon 4, 8/2/15, 2
  • Internet, Coupon 1, 6/1/15, 5
  • Internet, Coupon 1, 6/8/15, 4
  • Phone, Coupon 2, 8/2/15, 4
  • Phone, Coupon 1, 7/3/15, 10
  • Internet, Coupon 1, 6/5/15, 3

Desired Output:

  • Internet, Coupon 1, Monday, 9
  • Internet, Coupon 1, Friday, 3
  • Internet, Coupon 4, Sunday, 2
  • Phone, Coupon 1, Thursday, 6
  • Phone, Coupon 1, Friday, 10
  • Phone, Coupon 2, Sunday, 4
SELECT Source , Event, max(Qty) --or min of qty
,DateName(WEEKDAY,( TranDate )) As DayOfWk
FROM OurDB
GROUP BY Source, Event, DateName(WEEKDAY,( TranDate ))

Your query didnot have a aggregate function. From the expected result, it looks like you have to use a aggregate function on Qty column.

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