sql查询,结果中的每一列都是不同的WHERE子句

时间:2016-04-18 12:32:27

标签: sql sql-server

我正在尝试找到基于日期返回一些结果的最简单方法。 例如,表格就像这样

product     date     qty
corn        4/18/16   5
corn        4/18/16   1
corn        4/15/16   10

我希望结果是

product    4/15/16       4/18/16
corn        10              6

所以我按产品分组,加上数量,但结果中的每一列都是不同的WHERE filedate =。

有人可以指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT * FROM
(
    SELECT product,date,qty
    FROM Table1
)X 
PIVOT 
(
    SUM(X.qty) 
    FOR date IN([4/18/16],[4/15/16])
)Y

对于多个来源,您需要编写如下的动态查询

DECLARE @cols AS NVARCHAR(MAX),@query  AS NVARCHAR(MAX)

;WITH CTE (DATELIST, MAXDATE) AS
(
    SELECT '01/04/2016' DATELIST, '30/04/2016' MAXDATE
    UNION ALL
    SELECT DATEADD(dd, 1, DATELIST), MAXDATE
    FROM CTE
    WHERE DATELIST < MAXDATE
) 
SELECT C.DATELIST
INTO #TempDates
FROM CTE C


SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(convert(CHAR(10), DATELIST, 120)) 
                    FROM #TempDates
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = 'SELECT product,' + @cols + ' FROM 
             (
                SELECT B.product, B.date, B.qty, D.DATELIST, CONVERT(CHAR(10), DATELIST, 120) PivotDate
                FROM #TempDates D
                LEFT JOIN YourTable B ON D.DATELIST BETWEEN ''01/04/2016'' AND ''30/04/2016''
            ) X
            PIVOT 
            (
                SUM(qty)
                FOR PivotDate IN (' + @cols + ')
            ) P '

EXECUTE(@query)