连接两个选择查询以在同一表的一行中显示结果

时间:2018-07-09 13:12:34

标签: sql-server join select

希望这很简单,但我需要帮助。

我有两个查询,它们查找相同的数据,但具有不同的where语句。 数据显示了当日交易中不同卡牌的价值。但是,每个总计都在单独的一行上,因此id希望在商店的同一行上看到全部 因此[位置],[交易日期],[VISA],[AMEX],[#记录]。

我目前已将查询限制在一个位置。

任何帮助将不胜感激

查询A(签证记录)

SELECT 
 TILLREADREQUEST.STRTRADECODE AS [LOCATION]  
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(TILLREADDETAIL.CURVALUE) AS [VISA]
,COUNT(TILLREADREQUEST.ctrcode) AS [# RECORDS],

FROM          
 TILLREADDETAIL INNER JOIN
 TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE        (TILLREADDETAIL.INTTENDERCODE IN ('3')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by     TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE* 

查询B(美国运通记录)

SELECT 
 TILLREADREQUEST.STRTRADECODE AS [LOCATION]  
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(TILLREADDETAIL.CURVALUE) AS [AMEX]


FROM          
 TILLREADDETAIL INNER JOIN
 TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE        (TILLREADDETAIL.INTTENDERCODE IN ('4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by     TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE* 

2 个答案:

答案 0 :(得分:0)

在查询中针对特定条件使用CASE

SELECT 
 TILLREADREQUEST.STRTRADECODE AS [LOCATION]  
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('3')
   THEN TILLREADDETAIL.CURVALUE
   ELSE 0
   END
) AS [VISA]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('4')
   THEN TILLREADDETAIL.CURVALUE
   ELSE 0
   END
) AS [AMEX]
,COUNT(TILLREADREQUEST.ctrcode) AS [# RECORDS],

FROM          
 TILLREADDETAIL INNER JOIN
 TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE        (TILLREADDETAIL.INTTENDERCODE IN ('3', '4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by     TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE* 

答案 1 :(得分:0)

如果您还想分别计算VISA / AMEX的记录,则还必须在其中添加大小写。

SELECT 
 TILLREADREQUEST.STRTRADECODE AS [LOCATION]  
,TILLREADREQUEST.DTMTRADEDATE AS [TRADE DATE]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('3') THEN TILLREADDETAIL.CURVALUE ELSE 0 END) AS [VISA]
,SUM(CASE WHEN TILLREADDETAIL.INTTENDERCODE IN ('4') THEN TILLREADDETAIL.CURVALUE ELSE 0 END) AS [AMEX]
,COUNT(CASE WHEN TILLREADREQUEST.ctrcode = '3' THEN 1 ELSE NULL END) AS [# RECORDS],
,COUNT(CASE WHEN TILLREADREQUEST.ctrcode = '4' THEN 1 ELSE NULL END) AS [# RECORDS]
FROM          
 TILLREADDETAIL INNER JOIN
 TILLREADREQUEST ON TILLREADDETAIL.LINTREQUESTCODE = TILLREADREQUEST.CTRCODE
WHERE        (TILLREADDETAIL.INTTENDERCODE IN ('3','4')) and TILLREADREQUEST.DTMTRADEDATE > getdate()-2 AND STRTRADECODE = 'SHEFFIELD'
group by     TILLREADREQUEST.STRTRADECODE,TILLREADREQUEST.DTMTRADEDATE*