我有两个对SQL SERVER
数据库的查询,我想将两个查询的结果都连接起来,两个查询都显示结果。union
还是有什么帮助?但是合并合并所有记录时不显示两个查询列。
我的查询:
Select INITEMS.ITEMNO,
MAX(INITEMS.ITEMDESC#1) AS 'ITEMDESC',
SUM(INITEMS.QTY) 'Item Sale',
CONVERT(date, MAX(HDR.DATE)) as 'Last sale date'
FROM InvItems INITEMS
INNER JOIN InvHdr HDR ON HDR.INVNO=INITEMS.INVNO
WHERE INITEMS.TYPE = '3'
GROUP BY INITEMS.ITEMNO
Select WRK.ITEMEMPNO,
MAX(ITEMS.ITEMDESC#1) AS 'ITEMDESC',
SUM(WRK.QTY) 'Item Sale',
CONVERT(date, MAX(WRK.DATE)) as 'Last Use date'
FROM WRKTRANS WRK
INNER JOIN InvItems ITEMS ON WRK.ITEMEMPNO=ITEMS.ITEMNO
WHERE WRK.TYPE=1 AND WRK.STATUS=1 AND WRK.ISSUED=1 AND WRK.RECHARGE=0 AND
ITEMS.TYPE='3'
GROUP BY WRK.ITEMEMPNO
答案 0 :(得分:0)
如果您想使用UNION
,那么您可以这样做吗?
SELECT
i.ITEMNO,
MAX(i.ITEMDESC#1) AS ITEMDESC,
SUM(i.QTY) AS 'Item Sale',
'Last sale date' AS DateText,
CONVERT(DATE, MAX(HDR.DATE)) AS MyDate
FROM
InvItems i
INNER JOIN InvHdr HDR ON HDR.INVNO=INITEMS.INVNO
WHERE
i.TYPE = '3'
GROUP BY
i.ITEMNO
UNION ALL
SELECT
WRK.ITEMEMPNO,
MAX(ITEMS.ITEMDESC#1) AS ITEMDESC,
SUM(WRK.QTY) AS 'Item Sale',
'Last Use date' AS DateText,
CONVERT(DATE, MAX(WRK.DATE)) AS MyDate
FROM
WRKTRANS WRK
INNER JOIN InvItems ITEMS ON WRK.ITEMEMPNO=ITEMS.ITEMNO
WHERE
WRK.TYPE=1
AND WRK.STATUS=1
AND WRK.ISSUED=1
AND WRK.RECHARGE=0
AND ITEMS.TYPE='3'
GROUP BY
WRK.ITEMEMPNO;
或者,对于“八列混乱”,您可以执行以下操作:
SELECT
i.ITEMNO,
MAX(i.ITEMDESC#1) AS ITEMDESC AS ITEMDESC_1,
SUM(i.QTY) AS 'Item Sale_1',
CONVERT(DATE, MAX(HDR.DATE)) AS 'Last sale date',
NULL AS ITEMPNO,
NULL AS ITEMDESC_2,
NULL AS 'Item Sale_2',
NULL AS 'Last Use Date'
FROM
InvItems i
INNER JOIN InvHdr HDR ON HDR.INVNO=INITEMS.INVNO
WHERE
i.TYPE = '3'
GROUP BY
i.ITEMNO
UNION ALL
SELECT
NULL,
NULL,
NULL,
NULL,
WRK.ITEMEMPNO,
MAX(ITEMS.ITEMDESC#1) AS ITEMDESC_2,
SUM(WRK.QTY) AS 'Item Sale_2',
CONVERT(DATE, MAX(WRK.DATE)) AS 'Last Use date'
FROM
WRKTRANS WRK
INNER JOIN InvItems ITEMS ON WRK.ITEMEMPNO=ITEMS.ITEMNO
WHERE
WRK.TYPE=1
AND WRK.STATUS=1
AND WRK.ISSUED=1
AND WRK.RECHARGE=0
AND ITEMS.TYPE='3'
GROUP BY
WRK.ITEMEMPNO;