组合结果行

时间:2015-06-22 06:15:21

标签: sql sql-server tsql

我试图让下面的结果逐条显示。 这有可能吗?
所以最后我只有2行。 来自TYPE I& W将合并。

我的查询图像如下
image http://tikistudio.sg/F002.jpg

查询如下

SELECT INTSALEID as RECEIPT,
    STRSALETYPE as TYPE,
    STRORDERCODE as ARTICLE,
    max(case when strsaletype='I' then DBLQTYSOLD else null end) as [QTY SOLD],
    max(case when strsaletype='I' then CURSELLPRICE1 else null end) as [UNIT PRICE],
    max(case when strsaletype='W' then CUROFFERDISCOUNT else null end) as [DISCOUNT],
    max(case when strsaletype='I' then CURFOREIGNAMT else null end) as [GROSS AMOUNT]
FROM DAILYSALES 
WHERE STRTRADECODE='MM01' 
  and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
  and STRSALETYPE in ('I','W')
GROUP BY STRORDERCODE,STRSALETYPE,INTSALEID,DBLQTYSOLD,CURSELLPRICE1,
    CURFOREIGNAMT,CURDISCOUNT,CUROFFERDISCOUNT

2 个答案:

答案 0 :(得分:1)

您必须删除分组依据中的某些列

SELECT 
   INTSALEID as RECEIPT,
   STRORDERCODE as ARTICLE,
   MAX(CASE WHEN strsaletype='I' THEN DBLQTYSOLD ELSE NULL END) as [QTY SOLD],
   MAX(CASE WHEN strsaletype='I' THEN CURSELLPRICE1 ELSE NULL END) as [UNIT PRICE],
   MAX(CASE WHEN strsaletype='W' THEN CUROFFERDISCOUNT ELSE NULL END) as [DISCOUNT],
   MAX(CASE WHEN strsaletype='I' THEN CURFOREIGNAMT ELSE NULL END) as [GROSS AMOUNT]
FROM DAILYSALES 
WHERE 
STRTRADECODE='MM01' 
and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
and STRSALETYPE in ('I','W')
GROUP BY STRORDERCODE,INTSALEID

答案 1 :(得分:0)

如果您再次按收据和文章对数据进行汇总,则取出QTY Sold,Unit Price,Gross Amount和Min Value for discount的最大值。

Select RECEIPT, ARTICLE, MAX([QTY SOLD]) as [QTY SOLD], MAX([UNIT PRICE]) as [UNIT PRICE], MIN([DISCOUNT]) as [DISCOUNT], MAX([GROSS AMOUNT]) as [GROSS AMOUNT]
From
(select INTSALEID as RECEIPT,
STRSALETYPE as TYPE,
STRORDERCODE as ARTICLE,
max(case when strsaletype='I' then DBLQTYSOLD else null end) as [QTY SOLD],
max(case when strsaletype='I' then CURSELLPRICE1 else null end) as [UNIT PRICE],
max(case when strsaletype='W' then CUROFFERDISCOUNT else null end) as [DISCOUNT],
max(case when strsaletype='I' then CURFOREIGNAMT else null end) as [GROSS AMOUNT]
from DAILYSALES 
where STRTRADECODE='MM01' 
and DTMTRADEDATE='01-01-2015' and INTSALEID='31086'
and STRSALETYPE in ('I','W')
group by STRORDERCODE,STRSALETYPE,INTSALEID,DBLQTYSOLD,CURSELLPRICE1,
CURFOREIGNAMT,CURDISCOUNT,CUROFFERDISCOUNT) x
Group by RECEIPT, ARTICLE