早安全部 所以我被要求在每周的基础上看看订购的地方如此简单。
DECLARE @vYearWeek INT
SET @vYearWeek = '201745';
SELECT
LEFT(Orders.ProductWhsLocation,1) AS 'Area',
COUNT(Orders.HostOrderNo) AS 'Picked'
FROM CHDS_Common.dbo.OMOrder Orders
LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1)
ORDER BY LEFT(ProductWhsLocation,1);
这很好用......我现在需要更深入地把它洒进几天。现在逻辑会说这很简单:
DECLARE @vYearWeek INT
SET @vYearWeek = '201745';
SELECT
LEFT(Orders.ProductWhsLocation,1) AS 'Area',
CASE WHEN Cal.DW = 1 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Sunday',
CASE WHEN Cal.DW = 2 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Monday',
CASE WHEN Cal.DW = 3 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Tuesday',
CASE WHEN Cal.DW = 4 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Wednesday',
CASE WHEN Cal.DW = 5 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Thuresday',
CASE WHEN Cal.DW = 6 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Friday',
CASE WHEN Cal.DW = 7 THEN COUNT(Orders.HostOrderNo) ELSE 0 END AS 'Saturday'
FROM CHDS_Common.dbo.OMOrder Orders
LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1)
ORDER BY LEFT(ProductWhsLocation,1);
但是你们都知道错误:( 列'CHDS_Management.dbo.Calendar.DW'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。
任何有关排序的帮助都会非常感谢所有人。
答案 0 :(得分:1)
Pivot Query可以在这种情况下使用
- 改进答案
步骤1:在日历表或日期编号中按日期获取星期几
第2步:使用数据透视表按天获取行数
SELECT *
FROM
(
SELECT
LEFT(Orders.ProductWhsLocation,1) AS 'Area',
COUNT(Orders.HostOrderNo) OrderCount,
DATENAME(weekday,cal.dt) 'DayName'
FROM CHDS_Common.dbo.OMOrder Orders
LEFT JOIN CHDS_Management.dbo.Calendar Cal ON CONVERT(date, Orders.EarliestPickDate) = Cal.DT
WHERE Orders.PicksetNo <> 0 AND cal.YWK = @vYearWeek
GROUP BY LEFT(ProductWhsLocation,1),cal.dw
) AS SourceTable PIVOT(SUM(OrderCount) FOR [DayName] IN([SUNDAY]
,[MONDAY]
,[TUESDAY]
,[WEDNESDAY]
,[THURSDAY]
,[FRIDAY]
,[SATURDAY] )
) AS PivotTable;