我有点想要获取我在sqlserver表中拥有的唯一客户的数量。存储数据的方式是:
+----------+----------+----------+
| Value | Label | ClientID |
+----------+----------+----------+
| Mr | Title | 1 |
| Sul | Forename | 1 |
| Last | Surname | 1 |
| WD17 6JJ | Postcode | 1 |
+----------+----------+----------+
现在我必须根据姓,姓,邮政编码来计算\ list unique customer。有人可以帮忙吗
答案 0 :(得分:0)
了解不同客户的数量
SELECT COUNT (DISTINCT ClientId)
FROM dbo.table
或使用pivot获取不同的列表
DECLARE @Table TABLE ( [Value] NVARCHAR(20), Label NVARCHAR(20), ClientID INT)
INSERT INTO @Table
([Value], Label, ClientID)
VALUES
(N'Mr', N'Title', 1),
(N'Sul', N'Forename', 1),
(N'Last', N'Surname', 1),
(N'WD17 6JJ', N'Postcode', 1)
SELECT Pvt.Forename
, Pvt.Surname
, Pvt.Postcode
FROM @Table T
PIVOT ( MAX([Value]) FOR Label IN ([Title], [Forename], [Surname], [Postcode])) AS Pvt
GROUP BY
Pvt.Forename
,Pvt.Surname
,Pvt.Postcode
答案 1 :(得分:0)
您可以这样做:
SELECT DISTINCT
id.clientID,
title.title,
Forename.Forename,
Surname.Surname,
Postcode.Postcode
FROM table id
CROSS APPLY (SELECT value AS title FROM table title WHERE label = 'title' AND title.clientID = id.clientID ) title
CROSS APPLY (SELECT value AS Forename FROM table Forename WHERE label = 'Forename' AND Forename.clientID = id.clientID ) Forename
CROSS APPLY (SELECT value AS Surname FROM table Surname WHERE label = 'Surname' AND Surname.clientID = id.clientID ) Surname
CROSS APPLY (SELECT value AS Postcode FROM table Postcode WHERE label = 'Postcode' AND Postcode.clientID = id.clientID ) Postcode
它不漂亮,但应该有用。
答案 2 :(得分:0)
以下是两个可以提供所需结果的查询:
DECLARE @T table (Value varchar(255), Label varchar(255), ClientID int)
INSERT INTO @T
VALUES
('Mr', 'Title', 1)
, ('Sul', 'Forename', 1)
, ('Last', 'Surname', 1)
, ('WD17 6JJ', 'Postcode', 1)
, ('Dr', 'Title', 2) -- different Title will be ignored
, ('Sul', 'Forename', 2)
, ('Last', 'Surname', 2)
, ('WD17 6JJ', 'Postcode', 2)
, ('Mr', 'Title', 3)
, ('Sul2', 'Forename', 3) -- different Forename
, ('Last', 'Surname', 3)
, ('WD17 6JJ', 'Postcode', 3)
-- Using JOIN
SELECT DISTINCT
T1.Value Forename
, T2.Value Surname
, T3.Value Postcode
FROM
@T T1
JOIN @T T2 ON T1.ClientID = T2.ClientID AND T2.Label = 'Surname'
JOIN @T T3 ON T1.ClientID = T3.ClientID AND T3.Label = 'Postcode'
WHERE T1.Label = 'Forename'
-- Using PIVOT
SELECT DISTINCT
Forename
, Surname
, Postcode
FROM
(
SELECT
Value
, Label
, ClientID
FROM @T
) T
PIVOT
(
MAX (Value)
FOR Label IN
(
Forename, Surname, Postcode
)
) P