Это слишком долго для комментария и не отвечает той части, с которой вы сейчас боретесь, но весь ваш запрос может быть значительно упрощен с использованием псевдонимов, правильного синтаксиса объединения и некоторого форматирования примерно так:
SELECT it.trx_date
, datepart(day, datediff(day, 0, it.trx_date) / 7 * 7) / 7 + 1 AS WEEKNUMBER
, DATEPART(WEEK, DATEADD(month, DATEDIFF(month, 0, '".$datetime."'), 0)) + 1 AS WEEK_OF_MONTH
, it.trx_qty
, it.unit_price
, it.ord_qty
, i.prod_cat
, it.slsman_1
, SUM(it.trx_qty * it.unit_price) AS grand_total
FROM dbo.customer c
join dbo.inv_trx it on c.cust_no = it.cust_no
join dbo.item i on it.item_no = i.item_no
AND it.manu_no = i.manu_no
join dbo.ord_hedr oh on c.cust_no = oh.cust_no
AND it.order_no = oh.order_no
WHERE datepart(day, datediff(day, 0, it.trx_date) / 7 * 7) / 7 + 1 = 1
AND oh.ord_type in ('O', 'C')
AND it.trx_type = 'S'
AND oh.ord_class not in ('M', 'P')
AND c.exclude_sa = 0
AND YEAR(it.trx_date) = 2018 --date functions return integers not strings
AND MONTH(it.trx_date) = 7
GROUP BY it.trx_date
, DATEPART(WEEK, it.trx_date)
, it.trx_qty
, it.unit_price
, it.ord_qty
, i.prod_cat
, it.slsman_1
- РЕДАКТИРОВАТЬ -
Добавление примера ГРУППОВЫХ КОМПЛЕКТОВ.
Я бы взглянул на в этой статье , чтобы получить отличное объяснение того, как это работает.
SELECT it.trx_date
, datepart(day, datediff(day, 0, it.trx_date) / 7 * 7) / 7 + 1 AS WEEKNUMBER
, DATEPART(WEEK, DATEADD(month, DATEDIFF(month, 0, '".$datetime."'), 0)) + 1 AS WEEK_OF_MONTH
, it.trx_qty
, it.unit_price
, it.ord_qty
, i.prod_cat
, it.slsman_1
, SUM(it.trx_qty * it.unit_price) AS grand_total
FROM dbo.customer c
join dbo.inv_trx it on c.cust_no = it.cust_no
join dbo.item i on it.item_no = i.item_no
AND it.manu_no = i.manu_no
join dbo.ord_hedr oh on c.cust_no = oh.cust_no
AND it.order_no = oh.order_no
WHERE datepart(day, datediff(day, 0, it.trx_date) / 7 * 7) / 7 + 1 = 1
AND oh.ord_type in ('O', 'C')
AND it.trx_type = 'S'
AND oh.ord_class not in ('M', 'P')
AND c.exclude_sa = 0
AND YEAR(it.trx_date) = 2018 --date functions return integers not strings
AND MONTH(it.trx_date) = 7
GROUP BY GROUPING SETS((it.trx_date
, DATEPART(WEEK, it.trx_date)
, it.trx_qty
, it.unit_price
, it.ord_qty
, i.prod_cat
, it.slsman_1), ())