通过联合查询,将查询分为三个方面:
1、提出数据的基础明细,其代码如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
dbo.H_MORVE.QTY_RECVD1 AS Quantity, dbo.Key_item.Style AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
Order by Style asc
2、提出数据的一级汇总明细,其代码如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) AS Quantity,MAX(dbo.Key_item.Style) AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
GROUP BY dbo.Key_item.Style,dbo.Key_item.Key_item_name
order by Style
其结果如图如示:
3、提出数据的二级汇总明细,其代码如下:
SELECT MAX(dbo.Key_item.Key_item_name) as Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) as Quantity,
dbo.Key_item.Style as Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
GROUP BY dbo.Key_item.Style
ORDER BY dbo.Key_item.Style asc
其结果如图所示:
总体的设计就如以上所示,但通过UNION联接的时候出现了新的问题。通过以下例子,就可以看出UNION与UNION ALL的区别
方案一,其代码如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
dbo.H_MORVE.QTY_RECVD1 AS Quantity, dbo.Key_item.Style AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
UNION (
SELECT dbo.Key_item.Key_item_name AS Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) AS Quantity,MAX(dbo.Key_item.Style) AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
GROUP BY dbo.Key_item.Style,dbo.Key_item.Key_item_name
UNION
SELECT MAX(dbo.Key_item.Key_item_name) as Item_Name, SUM(dbo.H_MORVE.QTY_RECVD1) as Quantity,
dbo.Key_item.Style as Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
GROUP BY dbo.Key_item.Style)
ORDER BY dbo.Key_item.Style asc
GO
其结果如下:
问题:
通过以上结果,可以发现GR180.14.2.1后机架、PY165G.14.2.1B后机架和PY165K.14.2.1后机架的明细与其二级汇总值明显不符。而二级汇总的值是正确,为什么明细与汇总值不符?
针对这个问题,我采用了第二种方案。
方案二,其代码如下:
SELECT dbo.Key_item.Key_item_name AS Item_Name,
dbo.H_MORVE.QTY_RECVD1 AS Quantity, dbo.Key_item.Style AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
UNION ALL(
SELECT dbo.Key_item.Key_item_name AS Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) AS Quantity,MAX(dbo.Key_item.Style) AS Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
WHERE (dbo.Key_item.Key_item 1)
GROUP BY dbo.Key_item.Style,dbo.Key_item.Key_item_name
UNION
SELECT MAX(dbo.Key_item.Key_item_name) as Item_Name,
SUM(dbo.H_MORVE.QTY_RECVD1) as Quantity,
dbo.Key_item.Style as Style
FROM dbo.Key_item LEFT OUTER JOIN
dbo.H_MORVE ON dbo.Key_item.Key_item = dbo.H_MORVE.ITEM
GROUP BY dbo.Key_item.Style)
ORDER BY dbo.Key_item.Style asc
GO
其结果如图: