在运行时创建列

时间:2016-02-02 13:26:50

标签: sql-server sql-server-2008

我有一个查询

.midden ol {
    margin-top: 0;
    margin-bottom: 10px;
    display: table;
    margin: 0 auto;
}
.midden li{
  float: none;
}

.jumbotron {
    background: url("http://www.govisitcostarica.com/images/photos/full-hot-air-balloons-near-arenal.jpg") no-repeat scroll center center / cover;
    height: 720px;
    margin-top: -20px;
}

div h1 {
    font-family: 'Open Sans', sans-serif;
    font-weight: 400;
    font-size: 50px;
    color: white !important;
    text-align: center;
    margin-top: 0.2em;
}

p {
    font-family: 'Open Sans', sans-serif;
    font-size: 30px;
    color: white;
}

a {
    text-decoration: none;
    color: black;
    font-family: 'Open Sans', sans-serif;
    border: 3px solid black;
    padding: 10px 20px 10px 20px;
    display: inline;
    float: left;
    margin: 20px;
}

li {
    display: inline;
    float: right;
}

a:hover {
    text-decoration: none;
    background-color: #BDBFBD;
    color: white;
    border: 3px solid white;
}


/* Lookbook */

section {
    width: 80%;
    margin-left: auto;
    margin-right: auto;
}

.row-margin {
    margin-bottom: 20px;
    margin-top: 20px;
}

.img-responsive {
    display: block;
    max-width: 100%;
    height: auto;
}

.less-padding {
    padding: 0px;
}


/* Buttons */

li a {
    text-decoration: none;
    color: white;
    font-weight: 200 font-family: 'Roboto', sans-serif;
    border: 0.15em solid white;
    padding: 10px 20px 10px 20px;
    display: inline;
    float: left;
    margin: 20px;
}


li {
    display: inline;
    width: 120px;  
}

a:hover {
    text-decoration: none;
    background-color: #BDBFBD;
    color: white;
    border: 3px solid white;
    margin-bottom: 0px;
    margin-left: 20px;
}

它会显示电子邮件,但我想通过查询创建一个列,显示电子邮件总数。

请帮帮我

2 个答案:

答案 0 :(得分:1)

SELECT *, COUNT(1) OVER ()
FROM (
    SELECT DISTINCT EmailAddress
    FROM tblUsers
) t

仅限R& D -

CREATE FUNCTION dbo.udf_GetCount ()
RETURNS INT
WITH SCHEMABINDING
AS BEGIN
    RETURN (SELECT COUNT(DISTINCT EmailAddress) FROM tblUsers)
END
GO

ALTER TABLE dbo.tblUsers
    ADD TotalCnt AS dbo.udf_GetCount() PERSISTED
GO

SELECT DISTINCT EmailAddress, t.TotalCnt
FROM tblUsers
CROSS JOIN (
    SELECT TotalCnt = COUNT(DISTINCT EmailAddress)
    FROM tblUsers
) t

答案 1 :(得分:0)

<强>查询

name

如果您想要计算每封电子邮件,那么

CREATE TABLE #email
(
    email VARCHAR(MAX)
);

INSERT INTO #email VALUES
('a.c@s'),
('a.c@s'),
('b.c@s'),
('b.c@s'),
('c.c@s'),
('c.c@s'),
('d.c@s');

<强>结果

SELECT email, COUNT(email) AS [Count]
FROM #email
GROUP BY email;

否则总计不同的电子邮件数

+-------+-------+
| email | Count |
+-------+-------+
| a.c@s | 2     |
| b.c@s | 2     |
| c.c@s | 2     |
| d.c@s | 1     |
+-------+-------+

<强>结果

SELECT DISTINCT email, (SELECT COUNT(DISTINCT email)  FROM #email) AS [Count]
FROM #email;

SQL Fiddle demo