下午好。
我想从数据库中选择数据到下一个表:
结构数据库:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[ExPRoG_Statistic_banners](
[id] [int] IDENTITY(1,1) NOT NULL,
[user_id] [varchar](50) NULL,
[banner_idn] [varchar](50) NULL,
[banner_page] [varchar](150) NULL,
[action] [varchar](50) NULL,
[datetime] [datetime] NULL,
[server_referer] [varchar](150) NULL,
[ip] [varchar](50) NULL,
[browser] [varchar](500) NULL,
[id_firm] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
对于选择数据,我使用脚本:
SELECT * FROM ExPRoG_Statistic_banners WHERE banner_idn='50927853'
但是我看到选择表格中的所有数据,我需要使用31选择(每天)。
有没有人有任何想法如何使用较少数量的数据请求选择数据?
答案 0 :(得分:1)
试试这个 -
DECLARE @temp TABLE
(
items INT
, dt DATETIME
, [user_id] INT
)
INSERT INTO @temp (items, dt, [user_id])
VALUES
(1, '2013-08-08 00:00:000', 2),
(2, '2013-08-06 00:00:000', 1),
(5, '2013-08-05 00:00:000', 2),
(3, '2013-08-03 00:00:000', 1),
(2, '2013-08-02 00:00:000', 1),
(2, '2013-08-01 00:00:000', 1)
SELECT *
FROM (
SELECT
items
, [user_id]
, [day] = DAY(dt)
FROM @temp
WHERE dt BETWEEN '2013-08-01' AND '2013-08-31'
) src
PIVOT
(
SUM(items) FOR [day] IN (
[1], [2], [3], [4], [5], [6], [7], [8], [9], [10],
[11], [12], [13], [14], [15], [16], [17], [18], [19], [20],
[21], [22], [23], [24], [25], [26], [27], [28], [29], [30], [31])
) pvt
答案 1 :(得分:1)
看起来你想要pivot
select *
from
(
select id, DATEPART(d,[datetime]) dm from yourtable) s
pivot (count(id) for dm in
([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],-- etc...
)
) p