在SQL中生成二维结果表

时间:2011-04-21 19:47:59

标签: sql sql-server-2008

我有一个每天刷新的项目列表,其中每个项目属于四个价格区间之一。

以下查询将按日期提取每个价格区间中的项目计数,但它会将每个条带/日期组合放入其自己的行中。

SELECT PB.band, Count(L.ID) as Count
FROM ListItem L
join PriceBand PB on L.price >= PB.loprice and L.price <= PB.hiprice
Where ListID = 1  and ranking <= 100 and band >= 1 and band <= 4
Group by date, PB.band
order by date asc, band asc

结果集看起来像这样(两天用于说明):

date    band    Count
2010-12-08  1   20
2010-12-08  2   17
2010-12-08  3   32
2010-12-08  4   26
2010-12-09  1   19
2010-12-09  2   16
2010-12-09  3   33
2010-12-09  4   27

虽然我可以通过迭代来创建我真正想要的表,但是有一种合理的方法来编写查询以二维形式返回数据,如下所示:

date        band1   band2   band2   band3   
2010-12-08  20      17      32      26
2010-12-09  19      16      33      27

谢谢大家。

3 个答案:

答案 0 :(得分:4)

SELECT [date],
       COUNT(CASE WHEN PB.band = 1 THEN L.ID END) AS band1,
       COUNT(CASE WHEN PB.band = 2 THEN L.ID END) AS band2,
       COUNT(CASE WHEN PB.band = 3 THEN L.ID END) AS band3,
       COUNT(CASE WHEN PB.band = 4 THEN L.ID END) AS band4
FROM ListItem L
join PriceBand PB on L.price >= PB.loprice and L.price <= PB.hiprice
Where ListID = 1  and ranking <= 100 and band >= 1 and band <= 4
Group by date
order by date asc

答案 1 :(得分:3)

在T-SQL中查看PIVOT子句。 =&GT; MSDN Page

我不确定查询的确切形式,但它应该看起来像这样(如果有效,请告诉我):

SELECT [date],[1],[2],[3],[4]
FROM ListItem L
join PriceBand PB on L.price >= PB.loprice and L.price <= PB.hiprice
Where ListID = 1  and ranking <= 100 and band >= 1 and band <= 4
PIVOT(COUNT(L.ID) FOR PB.band IN([1],[2],[3],[4])) as pvt   
order by [date] asc

答案 2 :(得分:2)

首先,“date”是列的可怕的名称,所以我希望这只是一个例子。其次,由于你没有使用别名,我不知道它实际上是哪个表,所以这是我最好的猜测:

SELECT
    LI.list_date,
    SUM(CASE WHEN PB.band = 1 THEN 1 ELSE 0 END) AS band_1_count,
    SUM(CASE WHEN PB.band = 2 THEN 1 ELSE 0 END) AS band_2_count,
    SUM(CASE WHEN PB.band = 3 THEN 1 ELSE 0 END) AS band_3_count,
    SUM(CASE WHEN PB.band = 4 THEN 1 ELSE 0 END) AS band_4_count
FROM
    List_Item LI
INNER JOIN Price_Band PB ON
    PB.low_price <= LI.price AND
    PR.high_price >= LI.price AND
    PB.band <= 4
WHERE
    LI.list_id = 1 AND
    LI.ranking <= 100 AND
GROUP BY
    LI.list_date
ORDER BY
    LI.list_date