我不是SQL的专家。我有以下查询,我想要做的是将状态作为单个列移动并计算不同的actionid。
查询:
SELECT
CONVERT (Date,[ActionTime],103) AS DATE,
COUNT(DISTINCT ActionID) AS Actions,
VehicleID AS VehicleID,
DriverID AS DriverID,
CASE
WHEN ActionTypeID = 7 THEN 'Not Suitable'
WHEN ActionTypeID = 8 THEN 'Job Acknowledged'
WHEN ActionTypeID = 9 THEN 'Job Accepted'
WHEN ActionTypeID = 10 THEN 'Job Rejected'
WHEN ActionTypeID = 12 THEN 'Job Recall'
WHEN ActionTypeID = 66 THEN 'Child Fleet Logon'
WHEN ActionTypeID = 67 THEN 'Child Fleet Logoff'
ELSE '' END AS Status
FROM [TaxiHistory].[dbo].[Actions]
WHERE actiontime between '2016-02-01 00:00:00' AND '2016-02-02 23:59:59'
AND ActiontypeID IN (7,8,9,10,12,66,67)
GROUP BY CONVERT (Date,[ActionTime],103),
CASE
WHEN ActionTypeID = 7 THEN 'Not Suitable'
WHEN ActionTypeID = 8 THEN 'Job Acknowledged'
WHEN ActionTypeID = 9 THEN 'Job Accepted'
WHEN ActionTypeID = 10 THEN 'Job Rejected'
WHEN ActionTypeID = 12 THEN 'Job Recall'
WHEN ActionTypeID = 66 THEN 'Child Fleet Logon'
WHEN ActionTypeID = 67 THEN 'Child Fleet Logoff'
ELSE '' END,
VehicleID,
DriverID
答案 0 :(得分:0)
select
CONVERT (Date,[ActionTime],103) AS DATE,
COUNT(DISTINCT ActionID) AS Actions,
VehicleID AS VehicleID,
DriverID AS DriverID,
[7] 'Not Suitable',
[8] 'Job Acknowleged',
[9] 'Job Accepted',
[10] 'Job Rejected',
[12] 'Job Recall',
[66] 'Child Freet Logon',
[67] 'Child Fleet Logoff'
(
select ActionTime, VehicleId, DriverId, ActionTypeId, count(*) as TotalType
FROM [TaxiHistory].[dbo].[Actions]
WHERE actiontime between '2016-02-01 00:00:00' AND '2016-02-02 23:59:59'
AND ActiontypeID IN (7,8,9,10,12,66,67)
group by ActionTime, VehicleId, DriverId, ActionTypeId
pivot(sum(TotalType) for ActionTypeId in ([7],[8],[9],[10],[12], [66], [67]))
) p
内部查询是基本查询,它获取每个ActionTime,Vehicle,Deiver和ActionType的Actions数。 PIVOT的结尾基本上表示对于列出的每个ActionTypeId,总结TotalType并在结果集中放入一个名为ActionTypeId值的列。这个结果集(查询中的p)是外部选择的输入,它接受列并为其添加各种名称。
答案 1 :(得分:0)
我认为这是你正在尝试做的事情。
SELECT CONVERT (DATE,[ActionTime],103) AS [Date],
VehicleID AS VehicleID,
DriverID AS DriverID,
COUNT(CASE WHEN ActionTypeID = 7 THEN 1 END) AS [Not Suitable],
COUNT(CASE WHEN ActionTypeID = 8 THEN 1 END) AS [Job Acknowledged],
COUNT(CASE WHEN ActionTypeID = 9 THEN 1 END) AS [Job Accepted],
COUNT(CASE WHEN ActionTypeID = 10 THEN 1 END) AS [Job Rejected],
COUNT(CASE WHEN ActionTypeID = 12 THEN 1 END) AS [Job Recall],
COUNT(CASE WHEN ActionTypeID = 66 THEN 1 END) AS [Child Fleet Logon],
COUNT(CASE WHEN ActionTypeID = 67 THEN 1 END) AS [Child Fleet Logoff]
FROM [TaxiHistory].[dbo].[Actions]
WHERE actiontime BETWEEN '2016-02-01 00:00:00'
AND '2016-02-02 23:59:59'
AND ActiontypeID IN (7,8,9,10,12,66,67)
GROUP BY CONVERT (DATE,[ActionTime],103),
VehicleID,
DriverID