English 中文(简体)
需要一个有创意的SQL查询::帮忙
原标题:Need a Creative Sql Query :: HELP

我有一张表,一张简单的表,只有三个字段。

数据示例(记录集显示300个中的3个)

154页 | 2010年02月08日

154 | 链接 | 2010年02月08日

154 | 表格 | 2010年02月08日

Id:仅为客户提供的 ID

类型:只能是已经存在的三种事物(表格,页面,链接)

日期:创造日期

每个ID有多个条目。

我想创建一个存储过程或查询,以使我获得以下输出

期望的输出/计数示例

ID | 链接 | 表格 | 页面

154 | 75 | 40 | 100 一百五十四 | 七十五 | 四十 | 一百

我只想逐个计算,因此,我无需分别发出3个电话,以获得每个电话。 任何帮助都会受到高度赞赏,这将需要进入一个储存程序,而所有我都希望以此为基础。

提前致谢

最佳回答

你可能想要这样的东西。

Select id
, Sum(Case when Type= Link  then 1 else 0 end) as Links
, Sum(Case when Type= Forms  then 1 else 0 end) as Forms
, Sum(Case when Type= Page  then 1 else 0 end) as Pages
From SomeTable
Group by ID
问题回答

一个简单的 PIVOT 查询应该可以解决这个问题。

SELECT *
FROM SimpleTable 
PIVOT
(
    COUNT(Date)
    FOR Type IN ([Link], [Form], [Page])
) AS t

试试这个(SQL Server)

SELECT
    [ID]
        ,SUM( CASE TYPE WHEN  LINK  THEN 1 ELSE 0 END ) AS [Link]
        ,SUM( CASE TYPE WHEN  FORMS  THEN 1 ELSE 0 END ) AS [FORMS]
        ,SUM( CASE TYPE WHEN  PAGE  THEN 1 ELSE 0 END ) AS [Page]
    FROM yourTable
    GROUP BY ID       --remove this line if you are passing in a single @GivenID
    WHERE ID=@GivenID --remove this line if you want counts for all IDs (returns many rows)




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

难以执行 REGEXP_SUBSTR

I m 查询Oracle 10g。 我有两张表格(样本数据见下文)。 i m 试图提取一些领域

SQL Query Shortcuts

What are some cool SQL shorthands that you know of? For example, something I learned today is you can specify to group by an index: SELECT col1, col2 FROM table GROUP BY 2 This will group by col2

PHP array callback functions for cleaning output

I have an array of output from a database. I am wondering what the cleanest way to filter the values is example array Array ( [0] => Array ( [title] => title 1 ...

OracleParameter and DBNull.Value

we have a table in an Oracle Database which contains a column with the type Char(3 Byte). Now we use a parameterized sql to select some rows with a DBNull.Value and it doesn t work: OracleCommand ...

Running numbers in SQL

I have a SQL-statement like this: SELECT name FROM users WHERE deleted = 0; How can i create a result set with a running number in the first row? So the result would look like this: 1 Name_1 2 ...

How to get SQL queries for each user where env is production

I’m developing an application dedicated to generate statistical reports, I would like that user after saving their stat report they save sql queries too. To do that I wrote the following module: ...

热门标签