我需要最后一列AvgRecordCount为每两列的平均值;看一个例子的第一张图片......
有什么建议吗?
SELECT l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END AS LabelType,
COUNT(i.LabelTypeID) as RecordCount
FROM [RxTransaction] rxt
INNER JOIN Dimension.Item i
ON rxt.DispensedItemID = i.ItemID AND
rxt.LocationID = i.LocationID
INNER JOIN Dimension.Location l
ON rxt.LocationID = l.LocationId
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND
rxt.DateFilled BETWEEN '12/1/2014' AND '12/31/2014'
GROUP BY i.LabelTypeID, l.AltName
我希望看到此表中的项目结果,请注意两行中的新列百分比平均值,通用/品牌集。
图像显示了SQL和当前结果,我想要一个新的列,每列有2行百分比。
答案 0 :(得分:0)
您需要使用您在select语句中使用的确切CASE语句进行分组,例如....
SELECT l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END AS LabelType,
COUNT(i.LabelTypeID) as RecordCount
FROM [RxTransaction] rxt
INNER JOIN Dimension.Item i
ON rxt.DispensedItemID = i.ItemID AND
rxt.LocationID = i.LocationID
INNER JOIN Dimension.Location l
ON rxt.LocationID = l.LocationId
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND
rxt.DateFilled BETWEEN '12/1/2014' AND '12/31/2014'
GROUP BY l.AltName,
CASE
WHEN i.LabelTypeID = 1 THEN 'Generic'
WHEN i.LabelTypeID = 2 THEN 'Brand'
END
答案 1 :(得分:0)
我通过为我需要的每个计算字段编写select语句来解决这个问题...见下文。
SELECT L.AltName, L.LocationId, COUNT(A.LabelTypeID) As TotalRecords,
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE i.LabelTypeID = 1 AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014') As GenericTotal,
100
*
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE i.LabelTypeID = 1 AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014')
/
(SELECT COUNT(i.LabelTypeID)
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] rxt
INNER JOIN Dimension.Item i on rxt.DispensedItemID = i.ItemID AND rxt.LocationID = i.LocationID
WHERE (i.LabelTypeID = 1 OR i.LabelTypeID = 2) AND i.LocationID = L.LocationId AND
rxt.DateFilled between '12/1/2014' and '12/31/2014') As PercentAvg
FROM [IntellectRX-DataWarehouse].[Fact].[RxTransaction] B
INNER JOIN Dimension.Item A on B.DispensedItemID = A.ItemID AND B.LocationID = A.LocationID
INNER JOIN Dimension.Location L on B.LocationID = L.LocationId
WHERE B.DateFilled between '12/1/2014' and '12/31/2014'
Group by L.AltName, L.LocationId
order by PercentAvg