我在SQL Express 2016中遇到问题。 我在一个表中有打印跟踪数据,显示了:
现在,我正在尝试获取一个结果表,显示按设备序列号分组打印的总页数,然后是部门成本代码,最后是用户名。
输出理想情况如下:
Device Serial Cost Code User Name ColSpx ColDpx MonSpx MonDpx Price
CH238713498 2665473 Angela Rippon 43 22 245 566 £ 20
CH238713498 2665473 Warwick Davis 2 0 1000 230 £ 30
CH238713498 2623379 Carl Carlson 53 0 2145 1566 £ 55
CH238713498 2664443 Warwick Davis 2 0 1000 230 £ 30
我一直在使用的查询(并且没有成功更改)是:
DECLARE @ColourSimplex bigint SELECT TrackingPageCount
FROM TrackingTable
WHERE JobIsColor = 1 AND JobIsDuplex = 0 AND JobType < 4 AND TrackingState = 2 AND (UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%SYSTEM%') AND TrackingPageCount > 0
DECLARE @ColourDuplex bigint SELECT TrackingPageCount
FROM TrackingTable
WHERE JobIsColor = 1 AND JobIsDuplex = 1 AND JobType < 4 AND TrackingState = 2 AND (UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%SYSTEM%') AND TrackingPageCount > 0
DECLARE @MonoSimplex bigint SELECT TrackingPageCount
FROM TrackingTable
WHERE JobIsColor = 0 AND JobIsDuplex = 0 AND JobType < 4 AND TrackingState = 2 AND (UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%SYSTEM%') AND TrackingPageCount > 0
DECLARE @MonoDuplex bigint SELECT TrackingPageCount
FROM TrackingTable
WHERE JobIsColor = 0 AND JobIsDuplex = 1 AND JobType < 4 AND TrackingState = 2 AND (UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%SYSTEM%') AND TrackingPageCount > 0
SELECT DeviceModel,
UserCostCode,
UserLogon,
SUM(@ColourSimplex) AS 'Colour Simplex',
SUM(@ColourDuplex) AS 'Colour Duplex',
SUM(@MonoSimplex) AS 'Mono Simplex',
SUM(@MonoDuplex) AS 'Mono Duplex',
SUM(Price) AS 'Cost'
FROM TrackingTable
WHERE StartDateTime BETWEEN '2017-05-31 23:59:00' AND '2017-08-31 23:59:00'
GROUP BY DeviceModel,
UserCostCode,
UserLogon
ORDER BY DeviceModel, UserCostCode, UserLogon
以下是我得到的结果示例:
L7L3Y01090 100951 MARINA SIRBU NULL NULL NULL NULL 0.84
L7L3Y01090 A01016-DE06 MADELEINE MCALLISTER NULL NULL NULL NULL 0.168
L7L3Y01090 A02026-DE06 DANIEL POULTER NULL NULL NULL NULL 0.448
如何解决这个问题的任何帮助都将非常感激。
答案 0 :(得分:1)
SELECT DeviceModel,
UserCostCode,
UserLogon,
SUM(CASE WHEN JobIsColor = 1 AND JobIsDuplex = 0 AND JobType < 4 AND TrackingState = 2 AND (UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%name%' AND UserLogon NOT LIKE '%SYSTEM%') AND TrackingPageCount > 0 THEN TrackingPageCount ELSE 0 END) AS 'Colour Simplex',
SUM(Price) AS 'Cost'
FROM TrackingTable
WHERE StartDateTime BETWEEN '2017-05-31 23:59:00' AND '2017-08-31 23:59:00'
GROUP BY DeviceModel,
UserCostCode,
UserLogon
ORDER BY DeviceModel, UserCostCode, UserLogon
添加其他列...