多行选择子查询

时间:2011-08-12 18:49:11

标签: sql-server-2005 select

我有3个查询,他们工作正常。有查询是:

SELECT SUM(SALES)as NETSALES FROM Sales WHERE DOCREF='1'GROUP BY GEOCODE

以上查询结果:

NETSALES 
1
2 
3

 SELECT SUM(SALES)as FRESHRETURNS FROM Sales WHERE DOCREF='2'GROUP BY GEOCODE

以上查询结果:

FRESHRETURNS
1
2
3

 SELECT SUM(SALES)as SALESRETURNS FROM Sales WHERE DOCREF='3'GROUP BY GEOCODE

以上查询结果:

SALESRETURNS
1
2
3

有没有办法将这些语句组合起来得到结果

     NETSALES   |     FRESHRETURNS      |  SALESRETURNS
 1------1-------|-----------1-----------|--------1--------
 2------2-------|-----------2-----------|--------2--------
 3------3-------|-----------2-----------|--------3--------

4 个答案:

答案 0 :(得分:3)

如果您使用的是MS Sql Server或Oracle,我没有提及,我假设MS:)

利用CASE,您基本上可以构建一个包含所需结果的矩阵:

CREATE TABLE #t
 (
  Sale int,
  DocRef varchar(1),
  GeoCode varchar(1)
 )

INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(100, '1', 'A')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(120, '1', 'A')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(110, '2', 'B')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(120, '2', 'B')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(100, '3', 'C')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(100, '3', 'C')
INSERT INTO #t(Sale, DocRef,GeoCode) VALUES(100, '3', 'A')


SELECT 
      CASE WHEN DocRef='1' THEN SUM(Sale) ELSE 0 END as NETSALES,       
      CASE WHEN DocRef='2' THEN SUM(Sale) ELSE 0 END AS FRESHRETURNS,       
      CASE WHEN DocRef='3' THEN SUM(Sale) ELSE 0 END AS SALESRETURNS
FROM       
    #t 
GROUP BY       
    GeoCode,
    DocRef

DROP TABLE #t

答案 1 :(得分:0)

根据您使用的数据库产品,您可能需要稍微调整一下,但这样的事情对您有用:

SELECT GEOCODE, SUM(NETSALES), SUM(FRESHRETURNS), SUM(SALESRETURNS)
FROM
(
    SELECT GEOCODE, SUM(SALES)as NETSALES, 0 AS FRESHRETURNS, 0 AS SALESRETURNS FROM Sales WHERE DOCREF='1'GROUP BY GEOCODE
    UNION ALL
    SELECT GEOCODE, 0 AS NETSALES, SUM(SALES)as FRESHRETURNS, 0 AS SALESRETURNS FROM Sales WHERE DOCREF='2'GROUP BY GEOCODE
    UNION ALL
    SELECT GEOCODE, 0 AS NETSALES, 0 AS FRESHRETURNS, SUM(SALES)as SALESRETURNS FROM Sales WHERE DOCREF='3'GROUP BY GEOCODE
) AS salesData
GROUP BY GEOCODE

答案 2 :(得分:0)

我认为这有效,但我还没有测试过。我正在添加一个伪ID列,给它赋值'x'并使用这个新ID加入3个结果集:

select t.NETSALES, ta.FRESHRETURNS , tb.SALESRETURNS from 
(SELECT 'x' as ID, SUM(SALES)as NETSALES FROM Sales WHERE DOCREF='1'GROUP BY GEOCODE,ID ) as t

inner join 
(SELECT 'x' as ID, SUM(SALES)as FRESHRETURNS FROM Sales WHERE DOCREF='2'GROUP BY GEOCODE,ID) ta on ta.ID=t.ID

inner join 
(SELECT 'x' as ID SUM(SALES)as SALESRETURNS FROM Sales WHERE DOCREF='3'GROUP BY GEOCODE,ID ) tb on tb.ID=t.ID

答案 3 :(得分:0)

可能非常低效但在Oracle上适用于我

SELECT (SELECT SUM(SALES) FROM Sales WHERE DOCREF='1'GROUP BY GEOCODE) NETSALES,
   (SELECT SUM(SALES) FROM Sales WHERE DOCREF='2'GROUP BY GEOCODE) FRESHRETURNS ,
   (SELECT SUM(SALES) FROM Sales WHERE DOCREF='3'GROUP BY GEOCODE) SALESRETURNS FROM DUAL